Check text field text for NULL

Sorry for the nub question, but I have been trying to figure this out for over an hour. I use the following code to check for a null text field, and if it is zero, skip the copy to the clipboard and go to the rest of the code.

I don’t understand why I get the exception β€œThe value cannot be NULL”. Should he see zero and move on without copying to the clipboard?

private void button_Click(object sender, EventArgs e) { if (textBox_Results.Text != null) Clipboard.SetText(textBox_Results.Text); //rest of the code goes here; } 
+4
source share
3 answers

You should probably do your check this way.

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

Just an extra check, so if textBox_Results is ever null, you will not get a Null Reference exception.

+4
source

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

 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; } 
+5
source

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

 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 the use of the string.IsNullOrEmpty () method.

+1
source

All Articles