Best way to check whether a TextBox is empty or no

2019-05-18 12:16发布

I have a TextBox. And I want to check if it's empty.

Which way is better

if(TextBox.Text.Length == 0)

or

if(TextBox.Text == '')

?

3条回答
虎瘦雄心在
2楼-- · 2019-05-18 12:24

Farhan answer is the best and I would like to add that if you need to fullfil both conditions adding the OR operator works, like this:

if (string.IsNullOrEmpty(text.Text) || string.IsNullOrWhiteSpace(text.Text))
{
  //Code
}

Note that there is a difference between using string and String

查看更多
Melony?
3楼-- · 2019-05-18 12:40

I think

string.IsNullOrEmpty(TextBox.Text)

or

string.IsNullOrWhiteSpace(TextBox.Text)

are your best options.

查看更多
干净又极端
4楼-- · 2019-05-18 12:41

You should use String.IsNullOrEmpty() to make sure it is neither empty nor null (somehow):

if (String.IsNullOrEmpty(textBox1.Text))
{
    // Do something...
}

More examples here.

For practical purposes you might also consider using String.IsNullOrWhitespace() since a TextBox expecting whitespace as input probably negates any purpose, except in case of, say, letting the user pick a custom separator for stuff.

查看更多
登录 后发表回答