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();
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"  
   AllowPaging="true" DataKeyNames="ItemID" 
   DataSourceID="MyDataSource"  AutoGenerateInsertButton="true" 
<asp:label id="Message"    forecolor="Red"    runat="server"/>
<asp:SqlDataSource ID="MyDataSource"  
SelectCommand="SELECT ItemID,ItemName,ItemType,ClStk FROM ItemTable" 
runat="server"      />

protected void ItemsDetailsView_DataBound(object sender, EventArgs e)
	string temp=ItemsDetailsView.DataKey.Value.ToString();
	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"  
    <asp:SqlDataSource ID="MyDataSource"  
    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)"

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();
        string ID = DetailsView1.DataKey[0].ToString();