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?
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.
You should use String. IsNullOrEmpty() to make sure it is neither empty nor null (somehow): if (String. IsNullOrEmpty(textBox1.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With