Articles → .NET → Datakeynames Attribute In .Net

Datakeynames Attribute In .Net






Software Requirement





Prerequisite Knowledge




  1. What is a gridview control?
  2. How to bind data to a gridview control?
  3. How RowDataBound event in a gridview works?

Problem : Get The Value Of Primary Key Column In Gridview Control




Picture showing the gridview control with data bound with it
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




Picture showing how the datakeynames property is applied to the columns separated by comma
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 6, 2012

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250