How to get the DataKeys ID (Identity Column) in Child Controls events in GridView

Description:
 How to get the Datakeys ID in Child Control events, here I explained about checkbox

IDinChildControlEventsInGridView.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="IDinChildControlEventsInGridView.aspx.cs" Inherits="IDinChildControlEventsInGridView" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:GridView runat="server" ID="gvEmpdetails" DataKeyNames="EmpID" DataSourceID="EmpDetails"
AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" OnRowDataBound="gvEmpdetails_RowDataBound">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox runat="server"  ID="chkhead" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk" AutoPostBack="true" OnCheckedChanged="chk_OnCheckedChanged" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="EmpID" HeaderText="EmpID" Visible="false" SortExpression="EmpID" />
<asp:BoundField DataField="EmpName" HeaderText="EmpName" SortExpression="EmpName" />
<asp:BoundField DataField="EmpSal" HeaderText="EmpSal" SortExpression="EmpSal" />
<asp:BoundField DataField="EmpBranch" HeaderText="EmpBranch" SortExpression="EmpBranch" />
<asp:BoundField DataField="EmpCode" HeaderText="EmpCode" SortExpression="EmpCode" />           
</Columns>
</asp:GridView>
<%-- <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:CustomerConnectionString2 %>"
SelectCommand="SELECT [ID], [EmpID], [EmpTax], [EmpPF] FROM [EmpDeduction]">
</asp:SqlDataSource>--%>
<asp:SqlDataSource ID="EmpDetails" runat="server" ConnectionString="<%$ ConnectionStrings:CustomerConnectionString %>"
SelectCommand="SELECT [EmpID], [EmpName], [EmpSal], [EmpBranch], [EmpCode] FROM [Employee]">
</asp:SqlDataSource>
</asp:Content>



IDinChildControlEventsInGridView.aspx.cs

In the checkbox onCheckedchange event write the following code 
Identify the current gridview Row and then proceed further.

protected void chk_OnCheckedChanged(object sender, EventArgs e)
    {
        CheckBox  chk = ((CheckBox)(sender));
        GridViewRow gv = ((GridViewRow)(chk.NamingContainer));
        int EmpID =Convert.ToInt16(gvEmpdetails.DataKeys[gv.RowIndex].Value);
    }

 In the above EmpID we get the Empid For Which each row it is checked.



0 Responses to “How to get the DataKeys ID (Identity Column) in Child Controls events in GridView”

Post a Comment

Labels

Topics