检查文本框中的文本是否为空

5
我正在使用以下代码检查空文本框,如果为空,则跳过复制到剪贴板并继续执行其余代码。
我不明白为什么会出现“值不能为空”异常。它不应该在不复制到剪贴板的情况下跳过吗?
private void button_Click(object sender, EventArgs e)
{
    if (textBox_Results.Text != null) Clipboard.SetText(textBox_Results.Text);            

    //rest of the code goes here;
}

1
什么平台...Wpf?WinForms? - myermian
3个回答

7

您应该像这样执行检查:

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

这里需要进行额外的检查,以防万一textBox_Results为空,避免出现Null Reference异常。


2
它永远不应该是 null。除非您动态添加文本框或在表单被处理时尝试访问(极不可能),否则您应该没问题。请注意,您永远不应该尝试从另一个窗体访问 UI 控件。您应该通过方法来实现。 - tsells
使用 !String.IsNullOrWhiteSpace 使独立的 != null 检查变得多余。方法名称中明确指出它检查空值。 - TylerH
@TylerH!string.IsNullOrWhitespace被传递到textbox_Results.Text而不是textBox_Results。如果textbox_Results为空并且您访问.Text,它将在获取文本值以传递到string.IsNullOrWhitespace之前抛出空引用异常。话虽如此,使用较新版本的C#,我可以使用textBox_Results?.Text并删除第一个检查。 - Cubicle.Jockey

6

如果要检查 .Text 是否为空值,应该使用 String.IsNullOrEmpty() 函数,对于使用 .NET 4 的情况,也可以使用 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

我认为你可以检查文本是否为空字符串:

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()方法进行检查。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接