Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 检查文本框是否不为空_C# - Fatal编程技术网

C# 检查文本框是否不为空

C# 检查文本框是否不为空,c#,C#,如果我有两个文本框,并且我想知道它们的两个文本属性是否都为空,我可以这样做: if (string.IsNullOrWhiteSpace(txtNameFirst.Text) && string.IsNullOrWhiteSpace(txtNameLast.Text)) {} 这将检查两者是否都为null或空白,但是否有办法确定它们是否为null或空白?从本质上说,相反?放一个!在string.IsNullOrWhiteSpace方法调用之前 if (!str

如果我有两个文本框,并且我想知道它们的两个文本属性是否都为空,我可以这样做:

if (string.IsNullOrWhiteSpace(txtNameFirst.Text) && 
    string.IsNullOrWhiteSpace(txtNameLast.Text))
    {}
这将检查两者是否都为null或空白,但是否有办法确定它们是否为null或空白?从本质上说,相反?

放一个!在string.IsNullOrWhiteSpace方法调用之前

if (!string.IsNullOrWhiteSpace(txtNameFirst.Text) && 
    !string.IsNullOrWhiteSpace(txtNameLast.Text)) 
{
    // ...
}

有几种方法:

if (!string.IsNullOrWhiteSpace(txtNameFirst.Text) && 
    !string.IsNullOrWhiteSpace(txtNameLast.Text))
    {}


正如大家所说的那样!string.IsNullOrWhiteSpace适用于您

基于这个问题,我假设你不知道这个,但是逻辑否定运算符!是对其操作数求反的一元运算符。它是为bool定义的,当且仅当其操作数为false时才返回true


再举一个例子,假设我想看看狗大声吠叫的字符串是否包含字母a,我会键入string.Containsa。但是,如果我想确保它不包含字母a,我会打字!string.Containsa.

!string.IsNullOrWhiteSpace?您可以在语句前面加逻辑Not!喜欢string.IsNullOrWhiteSpacetxtNameFirst.text我以前没有遇到过.text?.property。你能给我指出一些关于用这种方式使用的“?”的进一步信息吗。谢谢@B.Hawkins如果文本以某种方式为null,那么访问Length不会抛出NullReferenceException,否则会抛出NullReferenceException。这意味着,这是一个空值的内联检查。@sebastianhofmannthank's。我意识到了??但接线员却没有遇到单身?以这种方式使用。@SebastianHofmann:虽然很好地演示了null条件运算符,但您的最后一个示例可能会失败,要么字符串只包含空格。它应该是txtNameFirst.Text?.Trim.Length>0
if (string.IsNullOrWhiteSpace(txtNameFirst.Text) == false && 
    string.IsNullOrWhiteSpace(txtNameLast.Text) == false)
    {}
if (txtNameFirst.Text?.Trim().Length > 0 && 
    txtNameLast.Text?.Trim().Length > 0)
    {}