Click here to Skip to main content
Click here to Skip to main content

DataKeyNames

, 22 Feb 2008
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Krishna Prasad Accottillam
Software Developer calicut
India India
Working in ASP.NET 2.0 C# in Kerala

Comments and Discussions

 
QuestionIs there a way to make checkbox selected once? PinmemberMember 1067281315-May-14 10:12 
GeneralHimalaya Pinmemberhimz_him17-Apr-10 22:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140821.2 | Last Updated 22 Feb 2008
Article Copyright 2008 by Krishna Prasad Accottillam
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid