检查文本框文本是否为空

时间:2013-01-16 01:51:29

标签: c# null

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

我不明白为什么我得到一个“Value not not 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;
}

3 个答案:

答案 0 :(得分:6)

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

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;
    }

答案 1 :(得分:5)

你应该像这样做你的支票:

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

只是额外检查,如果textBox_Results永远是null,则不会出现空引用异常。

答案 2 :(得分:1)

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

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

    //rest of the code goes here;
}

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