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

No comments:

Post a Comment