[RESOLVED] Refer to a checkbox using the counter
Hello
What I have is 10 checkboxes 1 to 10 which all can be one of several options (the options are constant for all the checkboxes) and I need to change a variable according to what the checkbox.text preperty contains.
I plan to use a For to next statement
Code:
For i = 0 to 9
If Checkbox(i+1).text = "hello" then
String(i) = "bye"
End If
If Checkbox(i+1).text = "sad" then
String(i) = "happy"
End If
Next i
However I cannot refer to a checkbox in the way i have done above.
Essentially how do get what the checkbox contains based on on my counter, i.
Note: it is i+1 because the first check box starts at one yet my counter starts at zero.
Cheers
TKP
Re: Refer to a checkbox using the counter
There a few ways to go here. Are there any other Checkbox's on the Form? Are they in a GroupBox (would be good if they were)?
Re: Refer to a checkbox using the counter
In line with what you had, here is a possible solution:
vb Code:
For i = 0 To 9
If Me.Controls("CheckBox" & i + 1).Text = "hello" Then
String(i) = "bye"
End If
If Me.Controls("CheckBox" & i + 1).Text = "sad" Then
String(i) = "happy"
End If
Next i
Now, reduced to:
vb Code:
For i = 0 To 9
If Me.Controls("CheckBox" & i + 1).Text = "hello" Then
String(i) = "bye"
ElseIf Me.Controls("CheckBox" & i + 1).Text = "sad" Then
String(i) = "happy"
End If
Next i
Re: Refer to a checkbox using the counter
Yes there are 10 CheckBoxes in a GroupBox called UserInput
Re: Refer to a checkbox using the counter
Thanks Bruce Fox it worked amazing
TKP
Re: [RESOLVED] Refer to a checkbox using the counter
What your also missing here is that you need to check those CheckBoxes that are selected, not just their Text property.
Re: [RESOLVED] Refer to a checkbox using the counter
Here is probably a better (dynamic) way, in that you can add or remove CheckBoxes without ther need to adjust Loop counters etc:
vb Code:
For Each ctl In Me.gbUserInput.Controls
' If the Control is a CheckBox, do something
If TypeOf ctl Is CheckBox Then
Dim cb = DirectCast(ctl, CheckBox)
' If the CheckBox is Selected, do something
If cb.CheckState = CheckState.Checked Then
If cb.Text = "hello" Then
String(i) = "bye"
ElseIf cb.Text = "sad" Then
String(i) = "happy"
End If
End If
End If
Next
Note, I prefixed 'UserInput' with gb in line with Hungarian Notation (to help identify the Control).