Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
457 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...