Articles → .NET → Datakeynames Attribute In .Net
Datakeynames Attribute In .Net
Software Requirement
Prerequisite Knowledge
- What is a gridview control?
- How to bind data to a gridview control?
- How RowDataBound event in a gridview works?
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