Using DetailsView control Datakeynames Property

To identify a record uniquely in the DetailsView control, the DataKeyNames property is used. To learn more about how the DataKeyNames property is used, read the article - Using GridView DataKeyNames property

The following example demonstrates how to set the DataKeyNames property of the DetailsView control.

<asp:DetailsView ID="DetailsView1" runat="server"  
AutoGenerateRows="true" 
AllowPaging="true" DataKeyNames="Code" 
DataSourceID="MyDataSource"   
AutoGenerateInsertButton="true"   
AutoGenerateEditButton="true">
</asp:DetailsView>

<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" 
InsertCommand="Insert SAMPLE(Code,Name,description) VALUES(@Code,@Name,@description)"
runat="server"/>


As in the GridView control, inserting, updating or deleting data in the DetailsView control is done using a DataSource control by setting the DataKeyNames property.

We can retrieve the DataKey value in the detailsView control using the following syntax:

Response.Write("Data key value: " & DetailsView1.DataKey.Value)

We can also assign multiple data keys to the DataKeyNames property. In the below code, we have assigned the multiple fields - Code and Name to the DataKeyNames property.

<asp:DetailsView ID="DetailsView1" runat="server"  AutoGenerateRows="true" 
   AllowPaging="true" DataKeyNames="Code,Name" 
   DataSourceID="MyDataSource"  OnPageIndexChanged="DetailsView1_PageIndexChanged"  
   AutoGenerateInsertButton="true"   
   AutoGenerateEditButton="true">
   </asp:DetailsView>


output of DetailsView control with Datakeynames Property

We can retrieve the multiple datakey values in the DataBound event of the DetailsView control using the below code.

 protected void ItemsDetailsView_DataBound(object sender, EventArgs e)
 {
   string ID = ItemsDetailsView.DataKey[0].ToString();
   string Name = ItemsDetailsView.DataKey[1].ToString();
 }


DetailsView Articles