Check for empty TextBox controls in VB.NET

2020-02-01 18:35发布

问题:

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?

回答1:

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


回答2:

I would recommend using the Validating event of the TextBox controls, with an error provider control (just add one to your form):

Private Sub TextBox_Validating( sender As System.Object,  e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating, TextBox2.Validating, ComboBox1.Validating
        Dim ctl As Control = CType(sender, Control)
        If ctl.Text = ""
            e.Cancel = True
            ErrorProvider1.SetError(ctl,"Please enter a value")
        End If
End Sub

Then you can just call:

ErrorProvider1.Clear()
If Me.ValidateChildren()
        ' continue on
End If

The nice thing about this is that the user is informed about which textbox is missing and required. This works with other controls besides textboxes, so you can provide a more complete solution. Also, if you get to a later point where one or two textboxes don't need to have values, you simply do not validate them instead of having to add special cases in your loops.

Finally, if you don't want to type out all of the controls, then you could do this in form load:

For Each c As Control In Me.Controls
    If TypeOf(c) is TextBox or TypeOf(c) is ComboBox
        AddHandler c.Validating, AddressOf Me.TextBox_Validating
    End If
Next


回答3:

A very simplistic approach would be to gather all the TextBox controls in a sequence using the Enumerable.OfType LINQ method and then iterate through it in a For Each loop:

Dim textBoxes = Me.Controls.OfType(Of TextBox);

For Each t In textBoxes
   If String.IsNullOrEmpty(t.Text) Then
       MsgBox("...")
       Exit For
   End If
Next t


回答4:

If TextBox field is empty then the message box will appear saying "Complete Entry!".

Dim t
For Each t In Me.Controls
    If TypeOf t Is TextBox Then
        If t.Text = "" Then
            MsgBox("Complete Entry!")
            Exit Sub
            Exit For
        End If
    End If
Next


回答5:

Sub for check Empty Textbox in GroupBox, you can use this:

Public Sub CheckEmptyTextbox(Byval groupbox as GroupBox)

Dim txt as control

For Each txt in groupbox.Controls

  IF TypeOF txt is Textbox then

     IF txt.Text="" Then


      MsgBox("Please Input data to textbox.")

      Exit For

     End IF

  End IF

Loop


End Sub


回答6:

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


回答7:

Public Class freestyle

Private Sub TextBox3_TextChanged(sender As Object, e As EventArgs) Handles TextBox3.TextChanged
    If Trim(TextBox3.Text) = "" And Me.Visible Then
        MsgBox("fill in the textbox")
        TextBox3.BackColor = Color.Yellow


    Else
        ' MsgBox("great one !!!")

    End If
End Sub

Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
    If Trim(TextBox2.Text) = "" And Me.Visible Then
        MsgBox("fill in the textbox")
        TextBox2.BackColor = Color.Yellow


    Else
        'MsgBox("great one !!!")

    End If
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click



    If Trim(TextBox1.Text) = "" Or Trim(TextBox2.Text) = "" Or Trim(TextBox3.Text) = "" And Me.Visible Then
        MsgBox("Please fill the necesary", MsgBoxStyle.Critical, "Error")
        TextBox1.Focus()

    Else
        MsgBox("Nice Work !!!")
    End If

End Sub

Private Sub TextBox1_Leave(sender As Object, e As EventArgs) Handles TextBox1.Leave
    If Trim(TextBox1.Text) = "" And Me.Visible Then
        MsgBox("fill in the textbox")
        TextBox1.BackColor = Color.Yellow


    Else
        ' MsgBox("great one !!!")

    End If
End Sub

End Class