Tuesday, February 19, 2013

Multiple DataKeyNames in GridView using c#

In this post i will show how to ADD multiple DataKeyNames in GridView and how to get(Read) them in the codebehind(RowCommand) using c#

ASPX page :


<asp:GridView ID="GridView1" runat="server" DataKeyNames="AdultID,ChildID" 
            AutoGenerateColumns="False" BackColor="White" BorderColor="#CC9966" 
            BorderStyle="None" BorderWidth="1px" CellPadding="4" 
            onrowcommand="GridView1_RowCommand">
            <Columns>
                <asp:BoundField DataField="AdultID" HeaderText="Adult ID" />
                <asp:BoundField DataField="CompanyName" HeaderText="Company" />
                <asp:BoundField DataField="ContactName" HeaderText="Name" />
                <asp:BoundField DataField="City" HeaderText="city" />
                <asp:BoundField DataField="Country" HeaderText="Country" />
                <asp:ButtonField HeaderText="Edit Entry" ButtonType="Button" CommandName="Edit" Text="Edit" />
                <asp:ButtonField HeaderText="Delete Entry" ButtonType="Button" CommandName="Delete" Text="Delete" />
            </Columns>
            <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
            <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
            <RowStyle BackColor="White" ForeColor="#330099" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
            <SortedAscendingCellStyle BackColor="#FEFCEB" />
            <SortedAscendingHeaderStyle BackColor="#AF0101" />
            <SortedDescendingCellStyle BackColor="#F6F0C0" />
            <SortedDescendingHeaderStyle BackColor="#7E0000" />
        </asp:GridView>


Code Behind :



protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int index = Convert.ToInt32(e.CommandArgument);
            int id = Convert.ToInt32(GridView1.DataKeys[index].Values["AdultID"]);
            string validation = GridView1.DataKeys[index].Values["ChildID"].ToString();
 
            switch (e.CommandName)
            {
                case "Edits":
                    // Edit Method
                    break;
                case "Delete":
                    // Delete Method
                    break;
            }
        }

No comments:

Post a Comment