Search code examples
asp.netentity-frameworktelerikentity-framework-6

get row value on update Button


See This Photo Plz

get the Product SKU Of the row which the button pressed

protected void On_Update_Click(object sender, EventArgs e)
{
}

Solution

  • The easiest way is to use the DataKeyNames property.

    <asp:GridView ID="GridView1" runat="server" DataKeyNames="SKU">
    

    And then you can access the correct DataKeyNames based on the Row Index.

    protected void On_Update_Click(object sender, EventArgs e)
    {
        //cast the sender back to a control and get the gridviewrow from the namingconainer
        GridViewRow row = (GridViewRow)(((Control)sender).NamingContainer);
    
        //get the gridview itself from the gridviewrow
        GridView gv = row.Parent.Parent as GridView;
    
        //get the correct datakey from the gridview with the dataitemindex
        int SKU = Convert.ToInt32(gv.DataKeys[row.DataItemIndex].Values[0]);
    
        //display result
        Label1.Text = SKU.ToString();
    }