Looping through controls?

  • Thread starter Thread starter Chris Devol
  • Start date Start date
C

Chris Devol

VB.NET 2002. I have a large group of CheckBoxes. I want to check/uncheck all
the boxes whenever the "Check All" box is checked/unchecked. I also want to
be able to fill an array of flags based on which boxes are
checked/unchecked.

Any way to do this kind of thing in a loop instead of writing a separate
line for each box?
 
Hi Chris

This is the sort of thing you need to do: loop through all your controls,
working out if you have a Checkbox. If you do, then check it / uncheck it
according to some condition.

For Each c As Control In Me.Controls
If TypeOf c Is CheckBox Then
Dim check As CheckBox = CType(c, CheckBox)
check.Checked = True
End If
Next

HTH

Nigel Armstrong
 
(I modified this from a recent project...)

You could generate the checkboxes dynamically in code:

(Put this in Load event on a form where you have a panel called Panel1.)

****Begin Code****
Dim Captions() As String = {"Check0", _
"Check1", "Check2", "Check3", "Check4", _
"Check5", "Check6", "Check7", "Check8", _
"Check9", "Check10", "Check11", "Check12", _
"Check13", "Check14", "Check15", "Check16", _
"Check17", "Check18", "Check19"}

Dim vSpace As Int32 = 22
Dim ColQuan As Int32 = 5
Dim W As Int32 = 70
Dim H As Int32 = 16
Dim Top As Int32 = 10
Dim TopMargin As Int32 = Top
Dim Left As Int32 = 20
Dim LeftMargin As Int32 = Left
Dim Vsep As Int32 = 22
Dim Hsep As Int32 = 105
Dim CB(Captions.GetUpperBound(0)) As CheckBox
Dim i As Int32
For i = 0 To CB.GetUpperBound(0)
CB(i) = New CheckBox()
With CB(i)
.Size = New Size(W, H)
.Text = Captions(i)
.Left = Left
.Top = Top
End With
Panel1.Controls.Add(CB(i))
If (i + 1) Mod ColQuan = 0 Then
Top = TopMargin
Left = (Hsep * ((i + 1) \ ColQuan)) + LeftMargin
Else
Top += Vsep
End If
Next
****End Code*****

You can change the number of checkboxes by modifying the number of Captions
in the Captions array. You can change how many captions are in a column by
changing ColQuan, spacing and margins with other variables.
You could arrange the checkboxes horizontally instead of vertically with
slight modifications.

To check which items are checked, or do a "CheckAll/UncheckAll, use a For
Each loop, as stated in the previous post, but use Panel1.Controls instead of
me.controls.

Use DirectCast to pass the current control in the loop to a checkbox variable.

Since the checkboxes ARE an array, you won't need to manage a separate
array.

www.charlesfarriersoftware.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

Back
Top