VB.NET中检查空的TextBox控件

9

我有一个VB.NET的表单应用程序。

在一个表单上有很多文本框(大约20个)。有没有办法一次性检查它们是否为空,而不是编写一长串代码逐个检查每个文本框,例如

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

这看起来只是一个绕远路的方式?

7个回答

23

您还可以使用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

有趣的方法是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

1
@Dr.Pepper:它的工作方式相同:Dim empty = Me.TabControl1.TabPages(1).Controls.OfType... - Tim Schmelter
啊哈,这就是我要找的字符串!我漏掉了“me.” 哈哈,谢谢伙计。 - Dr.Pepper
1
@Dr.Pepper:不,它可以没有“Me”,但不能使用“tabpage2”,而应该使用“TabPages(2)”,因为TabControl.TabPages是一个集合。 - Tim Schmelter
是的,我刚刚意识到了 - 漏掉了括号。谢谢 :) - Dr.Pepper
@Dr.Pepper 我们该如何修改 VB.Net 代码,使其能够将空文本框的背景颜色标记为黄色? - mightymax
显示剩余2条评论

7

我建议使用TextBox控件的验证事件,并使用错误提供程序控件(只需将其添加到表单中):

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

那么你只需要调用以下代码:
ErrorProvider1.Clear()
If Me.ValidateChildren()
        ' continue on
End If

这个方法的好处是用户可以知道哪个文本框是必填的。此方法也适用于除文本框之外的其他控件,因此您可以提供更全面的解决方案。另外,如果你到后来有一个或两个文本框不需要输入值,那么你只需不验证它们,而不是在循环中添加特殊情况。

最后,如果您不想输入所有的控件,那么您可以在表单加载时这样做:

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

我喜欢这个想法,只是它无法解决必须将所有20多个文本框输入到子程序中的问题。我正在寻找懒人的方法:P - Dr.Pepper
你可以在IDE中完成所有操作,只需将事件分配给文本框的验证事件即可。从长远来看,这可能会节省您的时间,因为您可以将所有验证逻辑放在一个地方。 - John Koerner
@JohnKoerner - 这太棒了!关于ErrorProvider1,有没有办法让我一次显示每个控件旁边的红色感叹号?现在它只对第一个识别为空的控件这样做。提前致谢。 - BobSki
我喜欢自动添加处理程序的那一部分,但是我遇到了“Option Strict On不允许晚期绑定”的问题。 - HackSlash

5

一个非常简单的方法是使用Enumerable.OfType LINQ 方法将所有的 TextBox 控件收集到序列中,然后在 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

你是指按顺序排列吗?比如txt1,txt2,txt3? - Dr.Pepper
你说的是像数组或 List(Of T) 这样的项目序列。你正在使用哪个 .NET Framework 版本?这是一个 WinForms 应用程序吗? - Enrico Campidoglio
使用Visual Studio 2010,为大学项目创建一般形式的应用程序。 - Dr.Pepper

1

检查 GroupBox 中的空文本框的替代方法,您可以使用以下代码:

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

1
如果TextBox字段为空,则会出现消息框,显示“完成输入!”。
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

1

我找到了这个,也许你可以修改它来检查所有文本框是否为空,而不是像它当前所做的那样只清除所有文本框

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

嗯,有趣,我会尝试并回报的。很好的创意思维;) 哈哈 - Dr.Pepper

-1

公共类自由泳

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

结束类


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接