Gridview datakeynames property

The DataKeyNames property is used to identify a record uniquely in the GridView control. A column in the data source is assigned to the DataKeyNames property to identify the record. To make this property work, the DataSource has to be bound to the GridView control. Normally, we assign the DataKeyNames property to the primary key field name of the database table. By doing so, we can identify the record in a Grid View control selected by the user.



The following example demonstrates how to set the DataKeyNames property of the GridView control.
<asp:GridView ID="GridView1" DataSourceId="MyDataSource" DataKeyNames="Code"
AutoGenerateEditButton="true" AutoGenerateDeleteButton="true" runat="server"/>
        
<asp:SqlDataSource ID="MyDataSource"  
ConnectionString="<%$Connectionstrings:ERPConnectionString%>"
SelectCommand="SELECT * FROM Sample" 
UpdateCommand="Update SAMPLE SET Name=@Name,Description=@Description Where Code=@Code"
DeleteCommand="Delete SAMPLE Where Code=@Code" runat="server"/>

When we are updating or deleting data in the GridView control using DataSource control, the DataKeyNames property has to be used. The DataSource control matches the values of key fields with the row to be updated or deleted.