Pronunciation / adjective
Bringing something good and unforseen.
    Skip Navigation Links > Code Repository
   

How to reference a checkbox or radiobutton, etc. in a DataGrid



 
Return

How to reference a checkbox or radiobutton, etc. in a DataGrid

How to loop through a datagrid to see if a checkbox in a column is checked.

First here's the grid as a reference: (I'm not showing how the data gets bound to it.)
  1. <asp:datagrid id="DataGrid1" runat="server">
  2. <columns>
  3. <asp:templatecolumn headertext="Correct">
  4. <itemtemplate>
  5. <asp:checkbox autopostback="True" oncheckedchanged="DataGridCheckBox_Changed" id="checkbox" runat="server" visible="True"></asp:checkbox>
  6. </itemtemplate>
  7. </asp:templatecolumn>
  8. <asp:boundcolumn datafield="Answer" headertext="Answer"></asp:boundcolumn
  9. </columns>
  10. </asp:datagrid>


And here's how to get the row's ItemIndex when you click the checkbox. (Note: the checkbox above is set to autopostback.)
  1. Protected Sub DataGridCheckBox_Changed(ByVal sender As System.Object, ByVal ByVale As System.EventArgs)
  2. '---Get the checkbox the user just clicked
  3. Dim cbSent As CheckBox = CType(sender, CheckBox)
  4. '---Prepare to loop through the datagrid
  5. Dim mintRowsCount, mintRowsLoop, mintCountChecked, mintAllowChecked As Integer
  6. Dim cbCurrent As CheckBox
  7. Dim mintRowIndexFound As Integer
  8. '---Get the number of rows in the datagrid
  9. mintRowsCount = DataGrid1.Items.Count() - 1
  10. '---Loop through each row
  11. For mintRowsLoop = 0 To mintRowsCount
  12. '---Get the current row's checkbox
  13. cbCurrent = CType(DataGrid1.Items(mintRowsLoop).FindControl("checkbox"), CheckBox)()
  14. '---Compare the current checkbox to the one clicked if they match this is the row!
  15. If cbCurrent.Equals(cbSent) Then
  16. '---Get the row's Index
  17. mintRowIndexFound = CInt(DataGrid1.Items(mintRowsLoop).ItemIndex)
  18. '---Exit the loop
  19. Exit For
  20. End If
  21. Next
  22. Response.Write(mintRowIndexFound.ToString)
  23. End Sub


Return
Microsoft Certified Professional   © 2018 Fortunate.  All rights reserved.
contact: justin@aboutfortunate.com