Problem solve Get help with specific problems with your technologies, process and projects.

How do you use control collection in VB.NET?

How do you use control collection in VB.NET? What I'm trying to do is find a quick way to pop up a message box if someone fails to input information into any text box on a form.
In WinForms, anything that ultimately derives from the Control base class, including the Form class, has a collection of container controls called Controls. In a Form or UserControl, the InitializeComponent method adds controls to this collection:

Private Sub InitializeComponent()
  Me.Button1 = New System.Windows.Forms.Button()
  Me.CheckBox1 = New System.Windows.Forms.CheckBox()
  Me.ComboBox1 = New System.Windows.Forms.ComboBox()
  Me.Label1 = New System.Windows.Forms.Label()
  Me.Controls.AddRange( _
    New System.Windows.Forms.Control() { _
      Me.Label1, _
      Me.ComboBox1, _
      Me.CheckBox1, _
End Sub

At any time, the control container can access these controls:

Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) _
  Handles MyBase.Load
  Dim control As Control
  For Each control In Me.Controls
End Sub

Based on this, you could handle the accept button on your form to check whether all text boxes have been filled with data:

Sub okButton_Click(ByVal sender As Object, ByVal e As EventArgs) _
  Handles okButton.Click
  Dim control As Control
  For Each control In Me.Controls
  ' Check each control to see if it's a TextBox
    If TypeOf (control) Is TextBox Then
      Dim textbox As TextBox = control
      ' Check each TextBox for Text
      If textbox.Text = "" Then
        ' Complain
        MessageBox.Show("Please enter text into all text boxes!")
        ' Set TextBox for input
        Me.ActiveControl = textbox
        ' Don't let the Form go away
        Me.DialogResult = DialogResult.None
        ' Stop checking
      End If
    End If
  ' Let the Form go away
  Me.DialogResult = DialogResult.OK
End Sub

For more information about Form data validation, see "WinForms Data Validation."

This was last published in January 2003

Dig Deeper on Win Development Resources

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.