Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for empty TextBox controls in VB.NET

Ive got a Form application in VB.NET.

I have many text boxes on one form (about 20). Is there anyway to check them all at once to see if they are empty instead of writing out a massive line of code to check each one individually such as

If txt1.text = "" Or txt2.text="" Then
    msgbox("Please fill in all boxes")

That just seems like a long way around it?

like image 854
Dr.Pepper Avatar asked Feb 28 '12 21:02

Dr.Pepper


People also ask

How check textbox is empty in VB net?

First declare emptyTextBoxes as the selection of any text property with length 0. then check if there is any textbox with length = 0 and show it.

Which of the following code is correct to check TextBox1 is blank?

You should use String. IsNullOrEmpty() to make sure it is neither empty nor null (somehow): if (String. IsNullOrEmpty(textBox1.

What is text box in VB net?

A TextBox control is used to display, accept the text from the user as an input, or a single line of text on a VB.NET Windows form at runtime. Furthermore, we can add multiple text and scroll bars in textbox control. However, we can set the text on the textbox that displays on the form.


2 Answers

I found this, perhaps you can modify it to check if all textboxes are clear rather than what it currently does which is just clear all textboxes

Public Sub ClearTextBox(ByVal root As Control)
For Each ctrl As Control In root.Controls
ClearTextBox(ctrl)
If TypeOf ctrl Is TextBox Then
CType(ctrl, TextBox).Text = String.Empty
End If
Next ctrl
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
ClearTextBox(Me)
End Sub
like image 192
Brent Hacker Avatar answered Oct 13 '22 16:10

Brent Hacker


You could also use LINQ:

Dim empty =
    Me.Controls.OfType(Of TextBox)().Where(Function(txt) txt.Text.Length = 0)
If empty.Any Then
    MessageBox.Show(String.Format("Please fill following textboxes: {0}",
                    String.Join(",", empty.Select(Function(txt) txt.Name))))
End If

The interesting method is Enumerable.OfType

The same in query syntax(more readable in VB.NET):

Dim emptyTextBoxes =
    From txt In Me.Controls.OfType(Of TextBox)()
    Where txt.Text.Length = 0
    Select txt.Name
If emptyTextBoxes.Any Then
    MessageBox.Show(String.Format("Please fill following textboxes: {0}",
                    String.Join(",", emptyTextBoxes)))
End If
like image 30
Tim Schmelter Avatar answered Oct 13 '22 16:10

Tim Schmelter