Is an empty textbox considered an empty string or

2019-01-15 06:37发布

The text box in question is involved in an if statement within my code, something to the effect of

if (textbox.text != "") 
{
    do this
}

I am curious if an empty text box will be considered an empty string or a null statement.

6条回答
SAY GOODBYE
2楼-- · 2019-01-15 07:21

It will be an empty string but better to check with this IsNullOrEmpty or IsNullOrWhiteSpace

if (!string.IsNullOrEmpty(textbox.text))
{
  //do this
}

IsNullOrWhiteSpace is also take care of whitespace in input string. So if you don't want to execute the code for whitespace too then use second option.

查看更多
祖国的老花朵
3楼-- · 2019-01-15 07:24

Try to use IsNullOrWhiteSpace, this will make sure of validating the whitespace too without having to trim it.

if (!string.IsNullOrWhiteSpace(textbox.Text))
{
    //code here
}

According to documentation string.IsNullOrWhiteSpace evaluates to:

return String.IsNullOrEmpty(value) || value.Trim().Length == 0;

String.IsNullOrWhiteSpace:

Indicates whether a specified string is null, empty, or consists only of white-space characters.

查看更多
唯我独甜
4楼-- · 2019-01-15 07:28

In short it will be an empty string, but you could use the debugger and check that yourself.

However for best practice use IsNullOrEmpty or IsNullOrWhiteSpace

if (!string.IsNullOrEmpty(textbox.Text)) {

}

Alternatively:

if (!string.IsNullOrWhiteSpace(textbox.Text)) {

}    

http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx

查看更多
Explosion°爆炸
5楼-- · 2019-01-15 07:28
string search = txtSearch.Text.Trim() != "" ? txtSearch.Text.Trim() : "0";
查看更多
虎瘦雄心在
6楼-- · 2019-01-15 07:29

if (textbox.text != "" || textbox.text != null)

查看更多
神经病院院长
7楼-- · 2019-01-15 07:32

It will be considered an empty string.

查看更多
登录 后发表回答