How to use a Check box in VB.Net code

Peter Hibbs 101 Reputation points
2021-03-06T12:22:43.45+00:00

Hi All,

I have a form with six Check boxes named chkCol1 to chkCol6 and I have a For/Next loop using a numeric variable called vCol.
I want to be able to set or clear any check box using the vCol variable as a reference, something like :-

**Controls("chkCol" & vCol).Checked = True**

except that this does not work. Is there any way to do this?

Peter Hibbs.

Developer technologies Windows Forms
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2021-03-06T13:00:45.89+00:00

    This should work:

    CType(Controls("chkCol" & vCol), CheckBox).Checked = True
    

    But if the controls are placed inside of some panel or groupbox, then specify the parent container, for example:

    CType(GroupBox1.Controls("chkCol" & vCol), CheckBox).Checked = True
    

    Or try a solution that searches all of the controls by name:

    CType(Controls.Find("chkCol" & vCol, True)(0), CheckBox).Checked = True
    
    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Ken Tucker 5,861 Reputation points
    2021-03-06T13:19:09.69+00:00

    You could try something like this

    Private Sub UncheckColCheckBoxes()
        Dim controlNames = {"chkCol1", "chkCol2", "chkCol3", "chkCol4", "chkCol5", "chkCol6"}
        For Each name As String In controlNames
            If Me.Controls(name) IsNot Nothing Then
                DirectCast(Me.Controls(name), CheckBox).Checked = False
            End If
        Next
    End Sub
    
    0 comments No comments

  2. Peter Hibbs 101 Reputation points
    2021-03-06T13:57:45.3+00:00

    Hi Viorel-1

    Thanks for that, it worked perfectly.

    Hi vb2ae,

    Thanks for your code, I have saved that as it could well be useful later on in my project.

    Peter Hibbs.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.