I would recommend using the Validating event of the TextBox controls with the error provider control (just add it to your form):
Private Sub TextBox_Validating( sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating, TextBox2.Validating, ComboBox1.Validating Dim ctl As Control = CType(sender, Control) If ctl.Text = "" e.Cancel = True ErrorProvider1.SetError(ctl,"Please enter a value") End If End Sub
Then you can just call:
ErrorProvider1.Clear() If Me.ValidateChildren() ' continue on End If
The best part is that the user is informed about which text field is missing and required. This works with controls other than text fields, so you can provide a more complete solution. Also, if you go to a later point when one or two text fields don't need values, you just don't check them, and don't add special cases to your loops.
Finally, if you do not want to enter all the controls, you can do this in the form of load:
For Each c As Control In Me.Controls If TypeOf(c) is TextBox or TypeOf(c) is ComboBox AddHandler c.Validating, AddressOf Me.TextBox_Validating End If Next
John kerner
source share