Articles → .NET → DataKeyNames attribute in .Net

DataKeyNames attribute in .Net


























Software requirement





Prerequisite knowledge











Problem : Get the value of Primary key column in

gridview control





Click to Enlarge



<asp:GridView ID="gvXMLBind" runat="server" AutoGenerateColumns="false" OnRowDataBound="gvXMLBind_RowDataBound">
  <Columns>
    <asp:BoundField DataField="ID" HeaderText="Employee ID" />
    <asp:BoundField DataField="name" HeaderText="Employee Name" />
  </Columns>
</asp:GridView>




protected void gvXMLBind_RowDataBound(object sender, GridViewRowEventArgs e)
{
        e.Row.Cells[0].Visible = false;
}







Problem with the approach





Solution : DataKeyNames attribute





Syntax


<asp:GridView runat="server" ID="<gridview_ID>" DataKeyNames="<list_of_field_names_separated_by_comma>"></asp:GridView>



Description of DataKeyNames attribute





Click to Enlarge


Resolution using DataKeyNames attribute




<asp:GridView ID="gvXMLBind" runat="server" AutoGenerateColumns="false" OnRowDataBound="gvXMLBind_RowDataBound" DataKeyNames="ID">
  <Columns>
    <asp:BoundField DataField="ID" HeaderText="Employee ID" />
    <asp:BoundField DataField="name" HeaderText="Employee Name" />
  </Columns>
</asp:GridView>




protected void gvXMLBind_RowDataBound(object sender, GridViewRowEventArgs e)
{        
  if (e.Row.RowType == DataControlRowType.DataRow)
  {            
      		/*      
            	gvXMLBind.DataKeys[e.Row.RowIndex][0]
              gvXMLBind.DataKeys[e.Row.RowIndex][1],   
              gvXMLBind.DataKeys[e.Row.RowIndex][2] 
              and so on for multiple values
         */
  }
}



Conclusion





Posted By  -  Karan Gupta
 
Posted On  -  Friday, January 06, 2012

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250