How do I reference a checkbox in code given a string?

M

Mason

I want to do a for loop through 45 check boxes, whose names are
CheckBox1 ... CheckBox 45. I'd like to do something like this:

Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnNext.Click

Dim i As Integer
Dim strCheckBox As String

For i = 1 To 45
strCheckBox = "CheckBox" & i
test = strCheckBox
If '***strCheckBox.Checked=True***
MsgBox(strCheckBox & "=True")
End If
Next
End Sub

I can't figure out how to reference a checkbox when I have only its
name. It should be a fairly simple piece of code, but I just can't
find it. Any help would be appreciated.

Thanks,

MW
 
M

Marina

Try:
Dim curCheckBox as CheckBox

....

curCheckBox = CType(Me.FindControl("CheckBox" & i),CheckBox)
 
H

Herfried K. Wagner [MVP]

* "Marina said:
Try:
Dim curCheckBox as CheckBox

...

curCheckBox = CType(Me.FindControl("CheckBox" & i),CheckBox)

For web forms. This won't work in Windows Forms.

\\\
Private Function FindControl( _
ByVal ControlName As String, _
ByVal CurrentControl As Control _
) As Control
Dim ctr As Control
For Each ctr In CurrentControl.Controls
If ctr.Name = ControlName Then
Return ctr
Else
ctr = FindControl(ControlName, ctr)
If Not ctr Is Nothing Then
Return ctr
End If
End If
Next ctr
End Function
///

Usage:

\\\
DirectCast(FindControl("Button1", Me), Button).Enabled = False
///

Notice that the procedure listed above is "slow", if you have to access a
lot of controls by name very often, you should store references to them in a
'Hashtable' object. You can use the name of the control as key:

\\\
Private m_Controls As New Hashtable()
///

Adding a control:

\\\
Dim DynamicPictureBox As New PictureBox()
DynamicPictureBox.Name = "PictureBox1"
m_Controls.Add(DynamicPictureBox.Name, DynamicPictureBox)
///

Looking for a control:

\\\
Dim p As PictureBox = DirectCast(m_Controls.Item("PictureBox1"), PictureBox)
///

Removing a control:

\\\
m_Controls.Remove("PictureBox1")
///

Sometimes it's even better to add the control to an array. This will allow
fast and easy index-based access to the control references:

\\\
Dim MyLabels() As Label = {Label1, Label2, ..., Label10}
///

Access by 'MyLabels(0)' to 'MyLabels(9)'.
 
G

Guest

or you can do a:
Dim checkboxes() As CheckBox = New CheckBox() {CheckBox1, CheckBox2}
For Each chk As CheckBox In checkboxes
chk.Checked = True


Next
Put as many check boxes in the array.
Hope that helps.
Abubakar.
http://joehacker.blogspot.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top