Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

DataKeyNames

4.72/5 (16 votes)
22 Feb 2008CPOL1 min read 2  
DataKeyNames property of Data presentation controls

One of the Important property of all the Data presentation controls in ASP.Net is the "DataKeynames" This is available in all of the data controls like GridView, DetailsView....etc. Most of the time we will assign the primary key of the data to this property . We can assign more that one data column value to this field, separated by a comma.This property need to be important at the time of updating a record from the data control.Now we can look one sample on how this datakeyNames were used in a DataGridView

DataKeyNames in GridView

Suppose I want to display an Employee details table data of a company. Here the user don't need to view the employee id in the table.But we were provided a checkbox on each rows corresponding to each employee, and a button provided bellow the Grid. On clicking this button, some action will take place for the checked rows data (here suppose we have to archive the checked row employee's data) . Then Our code will look like as bellow

Employee.aspx

<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
DataKeyNames="emp_id">
<Columns>
   <asp:BoundField DataField="fname" HeaderText="First name" SortExpression="fname" />
   <asp:BoundField DataField="lname" HeaderText="Last name" SortExpression="lname" />
   <asp:BoundField DataField="hire_date" HeaderText="Hire date" SortExpression="hire_date" />
   <asp:TemplateField HeaderText="Select">
       <ItemTemplate>
           <asp:CheckBox ID="CheckBox1" runat="server" />
       </ItemTemplate>
   </asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [emp_id], [fname], [lname], [hire_date] FROM [employee]">
</asp:SqlDataSource>

<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Archive" />
</div>
Employee.aspx.cs
public partial class Employee : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (((CheckBox)row.FindControl("CheckBox1")).Checked)
{

    int EmployeeID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
    //Archive the employee with this employee Id will goes from here
    ArchiveEmployee(EmployeeID);

}
}
}
}

Multiple DataKeyNames

Here If we want to to pass more than on field (for example we want to get the DepartmentID) then the the DataKeyNames will write like this
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
DataKeyNames="emp_id,dept_id">
 <Columns>
     <asp:BoundField DataField="fname" HeaderText="First name" SortExpression="fname" />
     <asp:BoundField DataField="lname" HeaderText="Last name" SortExpression="lname" />
     <asp:BoundField DataField="hire_date" HeaderText="Hire date" SortExpression="hire_date" />
     <asp:TemplateField HeaderText="Select">
         <ItemTemplate>
             <asp:CheckBox ID="CheckBox1" runat="server" />
         </ItemTemplate>
     </asp:TemplateField>
 </Columns>
</asp:GridView>
And in the Button1_Click event
protected void Button1_Click(object sender, EventArgs e)
{

foreach (GridViewRow row in GridView1.Rows)
{
  if (((CheckBox)row.FindControl("CheckBox1")).Checked)
  {

      int EmployeeID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0]);
      int DepartementID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[1]);


  }
}
}

Updating Data from DetailsView

It is important to set the dataKeyNames, while using ObjectDataSource to bind the details view.Here onclicking the Update button the ObjectDataSource will take Id value from the DataKeyNames of the DetailsView
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False"
 DataSourceID="ObjectDataSource1" DefaultMode="Edit"  DataKeyNames="Id">
    <Fields>
        <asp:TemplateField HeaderText="first name">
            <EditItemTemplate>
                <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("firstname") %>'></asp:TextBox>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Eval("firstname") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:CommandField ShowDeleteButton="True" ShowEditButton="True"  />
    </Fields>
</asp:DetailsView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" DeleteMethod="DeleteCustomer"
    SelectMethod="GetEmployeeById" TypeName="Employee
    UpdateMethod="UpdateEmployee">
    <DeleteParameters>
        <asp:Parameter Name="id" Type="Int32" />
    </DeleteParameters>
    <UpdateParameters>
        <asp:Parameter Name="id" Type="Int32" />
        <asp:Parameter Name="firstname" Type="String" />
    </UpdateParameters>
    <SelectParameters>
        <asp:QueryStringParameter Name="id" QueryStringField="id" Type="Int32" />
    </SelectParameters>
</asp:ObjectDataSource>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)