In this post we are going to see how to find checked checkboxes in gridview using c#. To find the checkboxes in gridview we have to iterate through the rows of gridview using gridviews rows collection. And then we can use findcontrol method of the row to get checkbox control. We need to pass Id of the checkbox to FindControl method.
In code behind on click of button we will iterate through gridviews rows and find out checked checkboxes.
Example to get checked checkboxes in gridview[C#]
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BorderWidth="1px"
CellPadding="3" BorderStyle="None" Font-Names="Arial">
<FooterStyle></FooterStyle>
<PagerStyle HorizontalAlign="Left"></PagerStyle>
<HeaderStyle Font-Bold="True"></HeaderStyle>
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CheckBoxSelect" runat="server" Enabled="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Item No." DataField="ItemNo">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Item Name" DataField="ItemName">
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
</asp:BoundField>
</Columns>
</asp:GridView>
</div>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</form>
</body>
</html>
In code behind on click of button we will iterate through gridviews rows and find out checked checkboxes.
using System.Data;
namespace aspnetcontrol
{
public partial class GridviewImages : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = BindImageData();
GridView1.DataBind();
}
}
public DataTable BindImageData()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("ItemNo", typeof(int)));
dt.Columns.Add(new DataColumn("ItemName", typeof(string)));
// Create the four records
DataRow dr = dt.NewRow();
dr["ItemNo"] = 1;
dr["ItemName"] = "Tea";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["ItemNo"] = 2;
dr["ItemName"] = "Coffie";
dt.Rows.Add(dr);
dr = dt.NewRow();
return dt;
}
protected void Button1_Click(object sender, EventArgs e)
{
// Iterate through the Products.Rows property
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("CheckBoxSelect");
if (cb != null && cb.Checked)
{
//Do some stuff
}
}
}
}