Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking Textbox Text for Null

Tags:

c#

null

I am using the following code to check for a null text-box, and, if it is null, skip the copy to clipboard and move on to the rest of the code.

I don't understand why I am getting a "Value cannot be NULL" exception. Shouldn't it see the null 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;
}
like image 527
Jeagr Avatar asked Jan 16 '13 01:01

Jeagr


People also ask

How check TextBox is empty in VB net?

First declare emptyTextBoxes as the selection of any text property with length 0. then check if there is any textbox with length = 0 and show it.

How check multiple TextBox is empty or not in C#?

foreach (Control c in this. Controls) { if (c is TextBox) { TextBox textBox = c as TextBox; if (textBox. Text == string. Empty) { // Text box is empty. // You COULD store information about this textbox is it's tag. } } }


1 Answers

You should probably be doing your check like this:

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

Just an extra check so if textBox_Results is ever null you don't get a Null Reference Exception.

like image 82
Cubicle.Jockey Avatar answered Sep 23 '22 21:09

Cubicle.Jockey