How to cycle through checkboxes in a datagrid and find out which ones are checked?

T

Tim Zych

I am trying to add a repeating checkbox to a datagrid and have some code
that can cycle through them and associate them with each row in the data
grid.

I was able to add the checkbox and I can see them, but I can't get a handle
on any of them when I cycle through them.

Here's what I have to add the checkbox.

<asp:templatecolumn HeaderText="Select">
<itemtemplate>
<asp:checkbox id="MyCheckbox" runat="Server" Enabled="true" />
</itemtemplate>
</asp:templatecolumn>

This "seems" to work because I can see the one checkbox for each row in the
data grid.

To test it out, I added a button and on the click, cycle through them and
try to find ones that are checked:

Viewing source of the datagrid web page, here's what I see:

<td>Excel</td><td>
<a id="dgTitles__ctl4_hl" href="readcode.aspx?CodeID=305">Unique Count</a>
</td><td>11/16/2005</td><td>11/16/2005</td><td>2</td><td>
<input id="dgTitles__ctl4_MyCheckbox" type="checkbox"
name="dgTitles:_ctl4:MyCheckbox" />
</td>

So I added some code to try to get a handle on them. I got this from google
and tried to modify it.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim dg As DataGrid = dgTitles
Dim dgi As DataGridItem
Dim s As String
Dim ctl As CheckBox
Dim i As Integer
For Each dgi In dg.Items
s = dgi.ClientID & "_MyCheckbox"
ctl = CType(dgi.FindControl(s), CheckBox)
If Not (ctl Is Nothing) Then
If ctl.Checked Then
i += 1
End If
End If
Next
Response.Write("total checked=" & i)
End Sub

No matter how I try to reference the checkbox, I can't get a handle on it.

How do I cycle through the checkboxes and find out which ones are checked?

thanks
 
S

Sundararajan

Hi,

try out the code like this. here the checkbox ids i have mentioned in the
template column is chkselect.

foreach(DataGridItem oDataGridItem in dgrd.Items)
{

chkselectASPx=(CheckBox) oDataGridItem.FindControl("chkSelect");
if(chkselectASPx.Checked)
{
}
else
{
}
}
 
T

Tim Zych

That works.

Here's the VB version:

For Each dgi In dg.Items
ck = CType(dgi.FindControl("MyCheckBox"), CheckBox)
If Not (ck Is Nothing) Then
If ck.Checked Then
i += 1
End If
End If
Next

Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top