The snippets provide basic approaches. More professional approaches are to:
- Create Custom Controls.
- Create and populate a Collection of related controls when the form is constructed.
- Encapsulate data in Classes - a Data Access Layer - together with..
- Using properties and events of the form (separating the GUI from the business logic)
Loop through just TextBoxes or other Controls
For Each tb As TextBox In Me.Controls.OfType(Of TextBox)() Next
Loop through just TextBoxes having a specific Tag or other property
For Each tb As TextBox In Me.Controls.OfType(Of TextBox)(). _ Where(Function(x) x.Tag = "Something") Next
A procedure to loop through ALL controls (including child controls) recursively
(or could use GetNextControl, which uses the TabIndex)
Sub AllControls(ByRef ctl As Control) For Each aCtl In ctl.Controls Debug.Print(aCtl.Name) If aCtl.HasChildren Then Call AllControls(aCtl) End If Next End Sub
The following looks for matching controls, CheckBoxes and TextBoxes that have similar/corresponding names. This is not a great approach. Better would be to:
- Create a Custom Control
- Use different controls!
- Create a Class to model the checkbox/textbox values in a single entity.
With the third suggestion a Collection of these objects could be maintained and events, such as the CheckBoxes' CheckedChanged event, used to modify the collection, or perhaps to add or remove items from the collection.
Anyway, suppose there are a list of checkboxes named "ckbFavourite1", etc., and related textboxes named "txtFavourite1", etc.. We loop through all the checkboxes to find those with names beginning "ckb". Replacing "ckb" with "txt" we can try to refer to a textbox having this name.
To demonstrate I just collect all of the text from textboxes (where their associated checkboxes are checked) and place this text on the clipboard.
'Checking controls in pairs, by similar name Dim clipbd As String = "" For Each cb As CheckBox In Me.Controls.OfType(Of CheckBox)() If cb.Name.StartsWith("ckb") AndAlso cb.Checked Then Dim sTextName As String = cb.Name.Replace("ckb", "txt") Dim tb As TextBox = TryCast(Me.Controls(sTextName), TextBox) If Not tb Is Nothing AndAlso Not String.IsNullOrWhiteSpace(tb.Text) Then clipbd &= tb.Text & vbNewLine End If End If Next If Not String.IsNullOrWhiteSpace(clipbd) Then My.Computer.Clipboard.SetText(clipbd) End If