检查VB.NET中的空TextBox控件

Dr.*_*per 8 .net vb.net textbox winforms

我在VB.NET中有一个Form应用程序.

我在一个表格上有很多文本框(大约20个).无论如何都要一次检查它们以查看它们是否为空而不是写出大量代码来单独检查每个代码,例如

If txt1.text = "" Or txt2.text="" Then
    msgbox("Please fill in all boxes")
Run Code Online (Sandbox Code Playgroud)

这看起来似乎还有很长的路要走?

Tim*_*ter 19

你也可以使用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
Run Code Online (Sandbox Code Playgroud)

有趣的方法是Enumerable.OfType

查询语法相同(在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
Run Code Online (Sandbox Code Playgroud)


Joh*_*ner 7

我建议使用TextBox控件的Validating事件,并使用错误提供程序控件(只需在表单中添加一个):

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
Run Code Online (Sandbox Code Playgroud)

然后你可以打电话:

ErrorProvider1.Clear()
If Me.ValidateChildren()
        ' continue on
End If
Run Code Online (Sandbox Code Playgroud)

关于这一点的好处是用户被告知缺少哪些文本框并且需要.这适用于除文本框之外的其他控件,因此您可以提供更完整的解决方案.此外,如果您稍后需要一个或两个文本框不需要值,您只需要验证它们,而不必在循环中添加特殊情况.

最后,如果您不想输入所有控件,那么您可以在表单加载中执行此操作:

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
Run Code Online (Sandbox Code Playgroud)


Enr*_*lio 5

一种非常简单的方法是TextBox使用Enumerable.OfType LINQ方法收集序列中的所有控件,然后在For Each循环中迭代它:

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
Run Code Online (Sandbox Code Playgroud)