-2

I am trying to detect empty text boxes when a button is pressed. To do so I am using an if statement for each variable like so:

If Len(variable.Text) = 0 Then 
   Messagebox.Show("please fill in all fields.")
End If 

Is there a more efficient way where I can detect if the lengths of the strings within all the text boxes are equal to zero at the same time? Or if anyone wants to suggest a better method that would also be appreciated. Thanks.

tomcorlett
  • 13
  • 4

2 Answers2

1

This would do, assuming the textboxes are in the same form as of the validation button

Dim ctrl As Control
For Each ctrl In Me.Controls ' panelname.controls etc
    If (ctrl.GetType() Is GetType(TextBox)) Then
        If Trim(ctrl.Text) = "" Then
            MessageBox.Show("please fill in all fields.")
            Exit Sub
        End If
    End If
Next

OR

Dim ctrl As Control
Dim count As Integer
count = 0
For Each ctrl In Me.Controls ' panelname.controls etc
    If (ctrl.GetType() Is GetType(TextBox)) Then
        If Trim(ctrl.Text) = "" Then count += 1
        'you can add exceptions by textbox name also by getting ctrl.Name
    End If
Next
If count > 0 Then
    MessageBox.Show("please fill in all fields.")
End If
VeteranLK
  • 717
  • 7
  • 17
0

That's the way to go. (:

If you want to check if all textboxes are empty (or in other words: is it possible to leave some textboxes empty or not) you could use something like this:

'if some textboxes can be empty
IF a="" AND b="" AND c="" Then Messagebox.Show("please fill in all fields.")

'if no textbox can be empty
IF a="" OR b="" OR c="" Then Messagebox.Show("please fill in all fields.")
Tom K.
  • 1,020
  • 1
  • 12
  • 28
  • 1
    [Difference between And and AndAlso](http://stackoverflow.com/questions/302047/what-is-the-difference-between-and-and-andalso-in-vb-net) and [Or vs OrElse](http://stackoverflow.com/questions/1170754/or-versus-orelse) – Steve Mar 05 '15 at 13:18