vb.netvariablesreferencecontrols

How do I reference controls with a variable in visual basic 2010?


I have 12 checkboxes (32 total, but for now just worrying about the first 12) that are named checkbox1, checkbox 2...checkbox 12. I want a for loop to go through them and see if they are checked. If they are checked, it makes changes to an excel sheet, if not it just continues. I have the logic for the spreadsheet edits and the basic structure of the for loop down, but don't know if there is a way to reference the controls using the counter in the for loop.

For example:

 for i as integer = 1 to 12
   if ("Checkbox" & i).checked = True Then
       <--Spreadsheet things happen-->
   End if
 then

I have had some people suggest a few things, namely using an array with the checkbox names and then doing checkboxes(i).checked but that leads to quite a few issues. Someone else suggested using controls.containskey and CType but while that doesn't give any compile or run time errors, nothing in the spreadsheet is actually changed and I have no idea what any of what I did means.

Does anyone know a simple way of doing this?


Solution

  • Use the Controls.Find() method:

        Dim matches() As Control
        For i As Integer = 1 To 12
            matches = Me.Controls.Find("CheckBox" & i, True)
            If matches.Length > 0 AndAlso TypeOf matches(0) Is CheckBox Then
                Dim cb As CheckBox = DirectCast(matches(0), CheckBox)
                If cb.Checked Then
    
                End If
            End If
        Next