Best way to check whether a TextBox is empty or not

落爺英雄遲暮 提交于 2019-12-06 04:23:22

问题


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 == '')

?


回答1:


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.




回答2:


I think

string.IsNullOrEmpty(TextBox.Text)

or

string.IsNullOrWhiteSpace(TextBox.Text)

are your best options.




回答3:


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



来源:https://stackoverflow.com/questions/34298857/best-way-to-check-whether-a-textbox-is-empty-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!