How to validate that at least one textbox was filled in (VB.Net)

1k views Asked by At

I have 4 textboxes, and I am trying to validate that at least one of the textboxes is filled before they hit search to check their search criteria.

My Problem: My code is working, but when I want to continue with one filled field, it still shows the messageBox.

If txtMember.Text = "" Then
            MessageBox.Show("Please enter a value!")
        ElseIf txtReference.Text = "" Then
            MessageBox.Show("Please enter a value!")
        ElseIf txtName.Text = "" Then
            MessageBox.Show("Please enter a value!")
        ElseIf txtCode.TextLength = "" Then
            MessageBox.Show("Please enter a value!")
        Else
            SearchClick()
        End If

How do I fix this? Your help would be much appreciated.

2

There are 2 answers

8
Cal-cium On BEST ANSWER

Is something like below what you want? So if every text box is blank you want a message box to appear otherwise if one of the text boxes is filled in then do SearchClick How to use If Else. Learning to step through the code, might have helped you realise what was happening in your code.

If txtMember.Text = "" AndAlso txtReference.Text = "" AndAlso txtName.Text = "" AndAlso  txtCode.TextLength = "" Then
    MessageBox.Show("Please enter a value!")
Else
    SearchClick()
End If
3
jmcilhinney On

The All and Any extension methods are useful in such cases, e.g.

If {TextBox1, TextBox2, TextBox3}.Any(Function(tb) tb.TextLength > 0) Then
    'At least one TextBox has some text in it.