检查文本框文本是否为空

Jea*_*agr 4 c# null

我使用以下代码检查空文本框,如果它为null,则跳过副本到剪贴板并转到其余代码.

我不明白为什么我得到一个"值不能为NULL"的例外.它不应该看到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;
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*mas 6

如果使用.NET 4 String.IsNullOrWhitespace()来检查.Text是否为Null值,则应使用String.IsNullOrEmpty().

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;
    }
Run Code Online (Sandbox Code Playgroud)


Cub*_*key 5

您应该像这样做我的支票:

if (textBox_Results != null && !string.IsNullOrWhiteSpace(textBox_Results.Text))
Run Code Online (Sandbox Code Playgroud)

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

  • 它永远不应该为空.除非您在处理表单时动态添加文本框或尝试访问(非常不可能),否则您应该没问题.请注意,您永远不应尝试从其他表单访问UI控件.你应该通过一种方法来做到这一点. (2认同)