如何检查文本框是否为空VB.Net

时间:2017-01-02 14:41:22

标签: vb.net

我想测试文本框是否为空以进行验证,而不是使用if x =""。相反,我想知道是否有更好的方法来做到这一点。目前我有:

If txtDob Is Nothing Or txtFirst Is Nothing Or txtGender Is Nothing Or txtLast Is Nothing Or txtPostcode Is Nothing Or txtStreetName Is Nothing Or txtStreetNo.Text Is Nothing Then
        MessageBox.Show("One or more fields have not been completed")
        Return
    End If

但是,这似乎不起作用,有人可以告诉我正确的方法或其他方法吗?

3 个答案:

答案 0 :(得分:1)

例如:

If String.IsNullOrEmpty(txtDob.Text) Then           
  ' "Contains Empty value or Null Value" 
End If 

答案 1 :(得分:0)

您需要检查Text属性。

If txtDob.Text = string.Empty Then

使用您的代码,您正在检查TextBox的对象是否为空,而不是内容。只要TextBox存在,您的条件就会返回false。

答案 2 :(得分:0)

你可以用这个:

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

Tim Schmelter关于Check for empty TextBox controls in VB.NET

的回答
相关问题