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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14350223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:33:28  来源:igfitidea点击:

Checking Textbox Text for Null

c#null

提问by Jeagr

I am using the following code to check for a null text-box, and, if it is null, skip the copy to clipboard and move on to the rest of the code.

我正在使用以下代码检查空文本框,如果它为空,则跳过复制到剪贴板并继续执行其余代码。

I don't understand why I am getting a "Value cannot be NULL" exception. Shouldn't it see the null and move on without copying to the clipboard?

我不明白为什么我会收到“值不能为 NULL”异常。它不应该看到空值并继续前进而不复制到剪贴板吗?

private void button_Click(object sender, EventArgs e)
{
    if (textBox_Results.Text != null) Clipboard.SetText(textBox_Results.Text);            

    //rest of the code goes here;
}

采纳答案by Cubicle.Jockey

You should probably be doing your check like this:

您可能应该像这样进行检查:

if (textBox_Results != null && !string.IsNullOrWhiteSpace(textBox_Results.Text))

Just an extra check so if textBox_Resultsis ever nullyou don't get a Null Reference Exception.

只是一个额外的检查,所以如果textBox_Results是以往null你没有得到一个空引用异常。

回答by Frazell Thomas

You should use String.IsNullOrEmpty(), if using .NET 4 String.IsNullOrWhitespace()to check .Text for Null values.

您应该使用String.IsNullOrEmpty(),如果使用 .NET 4 String.IsNullOrWhitespace()检查 .Text 的 Null 值。

private void button_Click(object sender, EventArgs e)
    {
        if (!String.IsNullOrEmpty(textBox_Results.Text) Clipboard.SetText(textBox_Results.Text);            

        //rest of the code goes here;
    }

回答by Nikola Metulev

I think you can just check if the Text is an empty string:

我认为您可以检查 Text 是否为空字符串:

private void button_Click(object sender, EventArgs e)
{
    if (textBox_Results.Text != "") Clipboard.SetText(textBox_Results.Text);            

    //rest of the code goes here;
}

You can also check using the string.IsNullOrEmpty() method.

您还可以使用 string.IsNullOrEmpty() 方法进行检查。