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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41428823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:14:06  来源:igfitidea点击:

How to check if a textbox is empty VB.Net

vb.net

提问by lrgthrill

I want to test if a textbox is empty for validation purposes, rather than using if x = "". Instead I was wondering if there was a better way to do this. Currently I have:

我想测试文本框是否为空以进行验证,而不是使用 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

However, this doesnt seem to work, can someone show me the correct method or another way to do this please?

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

回答by Dejan

For example:

例如:

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

回答by Juanche

You could use this:

你可以用这个:

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

Code from Tim Schmelter's answer on Check for empty TextBox controls in VB.NET

来自 Tim Schmelter 关于检查 VB.NET 中的空文本框控件的回答的代码

回答by Nik Bo

You need to check the Textproperty.

你需要检查Text财产。

If txtDob.Text = string.Empty Then

With your Code you're checking if the Object of your TextBox is nothing, not the content. As long as the TextBox exists, your condition would return false.

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