Monday, July 16, 2007

Assigning and accessing multiple values for DataKeyNames on a GridView

Multiple DB column values can be assigned to the DataKeyNames attribute of a GridView, and accessed in the code-behind as follows:

aspx markup:
asp:GridView ID="gv1" runat="server"
DataKeyNames="pk_parent_id, fk_child_id"


protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
int childId = (int)(gv1.DataKeys[e.Row.DataItemIndex].Values["fk_child_id"]);

protected void btn1_Click(object sender, EventArgs e)
foreach (GridViewRow row in gv1.Rows)
int childId = (int)(gv1.DataKeys[row.RowIndex].Values["fk_child_id"]);

No comments: