How To Set Multiple DataKeyNames in GridView

The following example demonstrates how to use the DataKeyNames property to specify the key field of the data source. In the example, the DataKeyNames attribute of the GridView element
in markup specifies two key fields by using a comma to separate the names.

aspx page
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
OnRowDeleting="GridView1_RowDeleting" DataKeyNames="ProductID,OrderID">
<Columns>

<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("ProductName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>   

 </Columns>
</asp:GridView>

C# code behind
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{

        //To retrieve the values from a DataKeyNames collection,
        //you can use "Key Names" or "index"

        //Get the values with key names
        string productId = GridView1.DataKeys[e.RowIndex].Values["ProductID"].ToString();
        string orderId = GridView1.DataKeys[e.RowIndex].Values["OrderID"].ToString();

        //Or

        //Get the values with index
        string productId = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
        string orderId = GridView1.DataKeys[e.RowIndex].Values[1].ToString();

}

0 comments:

Post a Comment