简体   繁体   English

空文本框是空字符串还是null?

[英]Is an empty textbox considered an empty string or null?

The text box in question is involved in an if statement within my code, something to the effect of 有问题的文本框涉及我的代码中的if语句,这是有效的

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

I am curious if an empty text box will be considered an empty string or a null statement. 我很好奇,如果一个空文本框将被视为空字符串或空语句。

Try to use IsNullOrWhiteSpace , this will make sure of validating the whitespace too without having to trim it. 尝试使用IsNullOrWhiteSpace ,这将确保验证空白,而不必修剪它。

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

According to documentation string.IsNullOrWhiteSpace evaluates to: 根据文档string.IsNullOrWhiteSpace评估为:

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

String.IsNullOrWhiteSpace : String.IsNullOrWhiteSpace

Indicates whether a specified string is null, empty, or consists only of white-space characters. 指示指定的字符串是空,空还是仅包含空格字符。

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 但是,对于最佳实践,请使用IsNullOrEmptyIsNullOrWhiteSpace

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

}

Alternatively: 或者:

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

}    

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

It will be an empty string but better to check with this IsNullOrEmpty or IsNullOrWhiteSpace 它将是一个空字符串,但最好检查一下这个IsNullOrEmptyIsNullOrWhiteSpace

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

IsNullOrWhiteSpace is also take care of whitespace in input string. IsNullOrWhiteSpace也会处理输入字符串中的空格。 So if you don't want to execute the code for whitespace too then use second option. 因此,如果您不想执行空格代码,请使用第二个选项。

它将被视为空字符串。

string search = txtSearch.Text.Trim() != "" ? txtSearch.Text.Trim() : "0";

if(textbox.text!=“”|| textbox.text!= null)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM