Skip to main content

DataKeyNames

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>

Comments

Popular posts from this blog

PNR Status by web Scraping Method (ASP.NET) C#

To Get the PNR Status by web Scraping Method Steps to Execute the Function Step 1 : Add the below method in your Form and Pass the PNR Number arguement public string GetPNRStatus( string sPNR) { string URI = "http://www.indianrail.gov.in/cgi_bin/inet_pnrstat_cgi.cgi" ; string Parameters = Uri .EscapeUriString( "lccp_pnrno1=" +sPNR+ "&amp;submitpnr=Get Status" ); System.Net. HttpWebRequest req = ( HttpWebRequest )System.Net. WebRequest .Create(URI); //HTTP POST Headers req.ContentType = "application/x-www-form-urlencoded" ; req.Host = "www.indianrail.gov.in" ; //You can use your own user-agent. req.UserAgent = "Mozilla/5.0 (compatible; MSIE 7.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0) DELL;Venue Pro" ; req.Headers.Add( HttpRequestHeader .AcceptLanguage, "en-us,en;q=0.5" ); req.Headers.Add( HttpRequestHeader .AcceptCharset, "ISO-8859-1,utf-8;q=
C# HttpClient tutorial C# HttpClient tutorial shows how to create HTTP requests with HttpClient in C#. In the examples, we create simple GET and POST requests. The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web. HttpClient  is a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. C# HttpClient status code HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes: Informational responses (100–199) Successful responses (200–299) Redirects (300–399) Client errors (400–499) Server errors (500–599) Program.cs using System; using System.Net.Http; using System.Threading.Tasks; namespace HttpClientStatus { class Program { static async Task Main(string[] args) { using var client = new

SonarQube Configuration For .NET Core Web API

When multiple developers are working on the same project, it's good to have a code review. SonarQube is a tool through which we can evaluate our code. Here, for demo purposes, we are going to evaluate the web API which is built on .NET Core. Let's see step by step implementation. In order to run SonarQube, we need to install JAVA in our local system.   Refer to the below link to download JAVA installer and install JAVA. https://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html Configure the 'PATH' system variable under environment variables Go to Control Panel > System > Advanced System Settings, it will open the System Properties window. Click on the "Environment Variables" button. Click on the "View" button under User Variables. Give the variable name as 'JAVA_HOME'. The variable value will be your JDK path where you installed JAVA. Select path variable under system variable and click o