How to find all the checked checkboxes in an asp.net gridview

I have seen this question a gazillion times on the forums – Finding checked checkboxes in an ASP.NET GridView. Here’s how to do so. The CheckBox in our example is in a TemplateField as shown below:

<asp:TemplateField>   
<
ItemTemplate >
<
asp:CheckBox id="CheckBox1" runat="server" />
</
ItemTemplate>
</
asp:TemplateField>



In order to find the checked checkboxes on a button click, use this simple code



C#



    protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvr in GridView1.Rows)
{
CheckBox chkBox = (CheckBox)gvr.FindControl("CheckBox1");
if (chkBox != null && chkBox.Checked)
{

}
}
}



VB.NET



Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As EventArgs)
For Each gvr As GridViewRow In GridView1.Rows
Dim chkBox As CheckBox = _
CType(gvr.FindControl("CheckBox1"), CheckBox)
If chkBox IsNot Nothing AndAlso chkBox.Checked Then
' Do Something
End If
Next gvr
End Sub






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: