Checking Textbox Text for Null

2019-02-18 08:53发布

问题:

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

回答1:

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.



回答2:

You should use String.IsNullOrEmpty(), if 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;
    }


回答3:

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



标签: c# null