Avoiding accessing DataGridItem.Cells[] - some old tricks
Some (working) sample code on how you can make your code safe from changes to the columns in a Datagrid and avoid accessing DataGridItem.cells[]
Specify a DataKeyField for your datagrid. This will assign a unique key to every row in your grid
<asp:DataGrid id=”dgAllRequirements” runat=”server” BackColor=”White” BorderColor=”Black” HorizontalAlign=”Center”
AutoGenerateColumns=”False” DataKeyField=”SubStepID”>
Then save the values you need in each row in hidden fields with unique names, using the same datafield you used for DataKeyField
<asp:TemplateColumn HeaderText=”Inv”>
<ItemTemplate>
<input type=hidden name=”hidInventorySite<%#DataBinder.Eval(Container.DataItem,”SubStepID”)%>” value=”<%#DataBinder.Eval(Container.DataItem,”InventorySiteCode”)%>”>
</ItemTemplate>
</asp:TemplateColumn>
Then access the hidden fields for the values you need
private void dgAllRequirements_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
string InventorySiteCode;
if (e.CommandName == “InventoryScan”)
InventorySiteCode = (string)Request[”hidInventorySite” + ((DataGrid)source).DataKeys[e.Item.ItemIndex]];
}
This will ensure your code will not break when someone adds new columns to the grid or makes some similar unrelated change (removes / moves a column).
Unless someone specifically modifies your code, this should be safe.
Specify a DataKeyField for your datagrid. This will assign a unique key to every row in your grid
<asp:DataGrid id=”dgAllRequirements” runat=”server” BackColor=”White” BorderColor=”Black” HorizontalAlign=”Center”
AutoGenerateColumns=”False” DataKeyField=”SubStepID”>
Then save the values you need in each row in hidden fields with unique names, using the same datafield you used for DataKeyField
<asp:TemplateColumn HeaderText=”Inv”>
<ItemTemplate>
<input type=hidden name=”hidInventorySite<%#DataBinder.Eval(Container.DataItem,”SubStepID”)%>” value=”<%#DataBinder.Eval(Container.DataItem,”InventorySiteCode”)%>”>
</ItemTemplate>
</asp:TemplateColumn>
Then access the hidden fields for the values you need
private void dgAllRequirements_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
string InventorySiteCode;
if (e.CommandName == “InventoryScan”)
InventorySiteCode = (string)Request[”hidInventorySite” + ((DataGrid)source).DataKeys[e.Item.ItemIndex]];
}
This will ensure your code will not break when someone adds new columns to the grid or makes some similar unrelated change (removes / moves a column).
Unless someone specifically modifies your code, this should be safe.
Comments
Post a Comment