How to get the datakey value in DetailsView control

To get the datakey value of the selected record of the DetailsView control, we need to set the DataKeyNames property of the DetailsView control. This property should be assigned with the Primary Key of the database table. After doing this, we can retrieve the DataKey value in the following ways.

string ID=ItemsDetailsView.DataKey.Value.ToString();
or
string ID = ItemsDetailsView.DataKey[0].ToString();

We can use the above code in the DataBound event of the DetilaView control to retrieve the DataKeys. The code to retrieve DataKey value in the DataBound event of detailsView control is given below.

<asp:DetailsView ID="ItemsDetailsView" runat="server"  
AutoGenerateRows="true" 
   AllowPaging="true" DataKeyNames="ItemID" 
   DataSourceID="MyDataSource"  AutoGenerateInsertButton="true" 
    OnDataBound="ItemsDetailsView_DataBound"
   AutoGenerateEditButton="true">
   </asp:DetailsView>
   
<br/>
<asp:label id="Message"    forecolor="Red"    runat="server"/>
<asp:SqlDataSource ID="MyDataSource"  
ConnectionString="<%$Connectionstrings:ERPConnectionString%>"
SelectCommand="SELECT ItemID,ItemName,ItemType,ClStk FROM ItemTable" 
runat="server"      />


protected void ItemsDetailsView_DataBound(object sender, EventArgs e)
 {
	string temp=ItemsDetailsView.DataKey.Value.ToString();
	//or
	string ID = ItemsDetailsView.DataKey[0].ToString();
 }



The code for retrieving the DataKey value in the PageIndexChanged event of detailsView control is given below.

<asp:DetailsView ID="DetailsView1" runat="server"  AutoGenerateRows="true" 
   AllowPaging="true" DataKeyNames="Code" 
   DataSourceID="MyDataSource"  OnPageIndexChanged="DetailsView1_PageIndexChanged"  
   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"/>


When the page index of the DetailsView control is changed, the PageIndexChanged event is fired. We cannot retrieve the datakey values as the data is not yet bound to the detailsView control. So, we call Databind() method in the PageIndexChanged event handler and then retrieve the datakey value as shown in the code given below.

protected void DetailsView1_PageIndexChanged(object sender, EventArgs e)
{
        //string ID = DetailsView1.DataKey.Value.ToString();
        DetailsView1.DataBind();
        string ID = DetailsView1.DataKey[0].ToString();
}