Reader Level:
ARTICLE

CheckBox in Gridview

Posted by Syed Shakeer Articles | ASP.NET Controls June 17, 2010
In this article you will know how to use the CheckBox inside Gridivew control and how to select the multiple checkboxes to get the selected CheckBoxes value will be displayed.
  • 1
  • 0
  • 36785

In this article you will know how to use the CheckBox inside Gridivew control and how to select the multiple checkboxes to get the selected CheckBoxes value will be displayed. 

First Drag and Drop one Gridview Control and Button on asp Page. Later retrieve the data from a table on Gridview using bound field and add on CheckBox field in .aspx source code page as shown below

<asp:GridView id="Gridview1" runat ="server" AutoGenerateColumns ="False" ShowFooter ="True"  DataSourceID ="SqlDataSource1" OnSelectedIndexChanged="Gridview1_SelectedIndexChanged" style="z-index: 101; left: 19px; position: absolute; top: 142px" BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None" Width="240px" >
<Columns >
<asp:TemplateField >
<ItemTemplate >
<asp:CheckBox ID="chk" runat ="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField  DataField ="ID" HeaderText ="ID" />
<asp:BoundField DataField="empname" HeaderText ="Name" />
<asp:BoundField DataField ="salary" HeaderText ="Salary" />
</Columns>
    <FooterStyle BackColor="Tan" />
    <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
    <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />
    <HeaderStyle BackColor="Tan" BorderColor="Fuchsia" BorderStyle="Solid" Font-Bold="True" />
    <AlternatingRowStyle BackColor="PaleGoldenrod" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
            ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="SELECT [ID], [empname], [salary] FROM [emp]">
</asp:SqlDataSource>
        
The output of above code is below: 

1.gif
 
Now I am writing code in GetValues Button to retrive values when the user selects one or more CheckBoxes.

protected void GetValues_Click(object sender, EventArgs e)
{
    for (int i = 0; i < Gridview1.Rows.Count; i++)
    {
        CheckBox chkb = (CheckBox)Gridview1.Rows[i].Cells[0].FindControl("chk");
        if (chkb.Checked)
        {
            string name = Gridview1.Rows[i].Cells[2].Text;
            Response.Write("<br>" + name);
        }
    }
}
 
Click on GetValues Button after selecting one or more CheckBoxes, then you will get values that you had checked in gridview.

The output is show below:

2.gif

erver'>
COMMENT USING

Trending up