CODEDIGEST
Home » CodeDigest
Search
 

Technologies
 

How to Get DataKey value in RowDataBound or RowCommand Event in ASP.Net GridView control ?
Submitted By Satheesh Babu B
On 3/17/2010 9:36:11 AM
Tags: ASP.Net,C#,CodeDigest  

How to Get DataKey value of a Row in RowDataBound or RowCommand Event in ASP.Net GridView control ?

 

We will normally set the primary key field to the DataKeyNames property of GridView control to identify the row. This little code snippet will help us to find the data keys assocciated with a row in DataBound and RowCommand event in codebehind file.

 

Refer the below code,
ASPX
  <asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False"
            DataKeyNames="UserID" OnRowDataBound="gvUsers_RowDataBound"
            RowStyle-CssClass="Row" onrowcommand="gvUsers_RowCommand">
                    <Columns>                      
                        <asp:BoundField DataField="FirstName" HeaderText="First Name" ReadOnly="True" />
                        <asp:BoundField DataField="LastName" HeaderText="Last Name" ReadOnly="True" />     
                         <asp:BoundField DataField="Email" HeaderText="Email" ReadOnly="True" /> 
                         <asp:TemplateField>
                         <ItemTemplate>
                        <asp:Button runat="server" Text="SELECT" CommandName="Select" />                             
                        </ItemTemplate>
                         </asp:TemplateField>                       
                    </Columns>                   
                    <HeaderStyle BackColor="#F06300" Font-Bold="True" ForeColor="#FFFFCC" />
     </asp:GridView>

 

RowDataBound Event
protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
    {       
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            object objTemp = gvUsers.DataKeys[e.Row.RowIndex].Value as object;
            if (objTemp != null)
            {
                string id = objTemp.ToString();
 //Do your operations
            }
          
        }
    }

 

RowCommand Event
    protected void gvUsers_RowCommand(object sender, GridViewCommandEventArgs e)
    {
      Control ctl = e.CommandSource as Control;
      GridViewRow CurrentRow = ctl.NamingContainer as GridViewRow;
      object objTemp = gvUsers.DataKeys[CurrentRow.RowIndex].Value as object;
      if (objTemp != null)
      {
          string id = objTemp.ToString();
 //Do your operations
      }
    }

Do you have a working code that can be used by anyone? Submit it here. It may help someone in the community!!

Recent Codes
  • View All Codes..