Requires Free Membership to View
When you register, you'll begin receiving targeted emails from my team of award-winning writers. Our goal is to provide a unique online resource for developers, architects and development managers tasked with building and maintaining enterprise applications using Visual Basic, C# and the Microsoft .NET platform.
Hannah Smalltree, Editorial Director
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, _
Me.Button1})
...
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
MessageBox.Show(control.Name)
Next
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
Return
End If
End If
Next
' Let the Form go away
Me.DialogResult = DialogResult.OK
Me.Close()
End Sub
For more information about Form data validation, see "WinForms Data Validation."
This was first published in January 2003