检查文本框文本是否为空

我使用以下代码检查空文本框,如果它为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; } 

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

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

只是一个额外的检查,所以如果textBox_Results永远为null你不会得到一个空引用exception。

如果使用.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; } 

我想你可以检查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()方法进行检查。