1

I have an USB controller, Xk-60 from P.I. Engineering, is configure and working properly. The following code read if a key is pressed on the controller and select a case based on the returned CID value. All good until here. Now a like to refer to several Checkbox dynamically also using the CID value. I don't seem to find the right way ...

This is not valid:

If e.PressState = True And **ctl.Checked** = False Then

Private Sub Xk60_80_1_ButtonChange(ByVal e As XK_60_80.XKeyEventArgs) Handles Xk60_80_1.ButtonChange
    Select Case e.CID
        Case 1001
            Dim nbr As String = e.CID.ToString().Remove(0, 3)
            Dim ctl() As Control = Me.Controls.Find("CheckBox" & nbr, True)
            If e.PressState = True And ctl.Checked = False Then              
                CheckBox1.Checked = True
            ElseIf e.PressState = True And CheckBox1.Checked = True Then
                CheckBox1.Checked = False
            End If
    End Select
End Sub

2 Answers 2

2

Me.Controls.Find returns an array of controls.
Also Control has no Checked-property so it's better to search only the controls of type CheckBox and use the first found with the appropriate name:

Dim ctl As CheckBox = Me.Controls.OfType(Of CheckBox).
                      First(Function(c) c.Name = "CheckBox" & nbr)

If e.PressState = True AndAlso ctl IsNot Nothing AndAlso ctl.Checked = False Then
    CheckBox1.Checked = True
ElseIf e.PressState = True And CheckBox1.Checked = True Then
    CheckBox1.Checked = False
End If

Also it's better to use short-circuiting like already mentioned in Tim Schmelter's answer.

Sign up to request clarification or add additional context in comments.

3 Comments

This approach has one drawback. Unlike Controls.Find Controls.OfType is not searching for the control recursively. So if it's contained in a child control like a Panel you won't find it.
Or cycle i from 0 to ctl.count-1 and set ctl(i).enabled = False
Great this works for me. Not searching recursively is a drawback indeed. Thanks you all.
2

Controls.Find returns a Control(), so possibly multiple controls. If you want the first:

Dim checkBoxControl = TryCast(ctl.ElementAtOrDefault(0), CheckBox)

CheckBox1.Checked = e.PressState AndAlso 
                    checkBoxControl IsNot Nothing AndAlso 
                    Not checkBoxControl.Checked

Note that i have used AnsAlso instead of And which is a short-circuiting operator which stops if the previous condition is not met. Otherwise you would get a NullReferenceException at checkBoxControl.Checked if checkBoxControl was already Nothing. So use AndAlso(and OrElse).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.