Piotr Nawrot
Piotr Nawrot

Reputation: 445

Check if textbox is empty - is there a better way?

I want to check if textbox is not empty.

Is there a better (more elegant, simpler) way than:

String.IsNullOrWhiteSpace(null == txtBox ? null : txtBox.Text)

It is worth to note that String.IsNullOrWhiteSpace(txtBox.Text) throws NullReferenceException if txtBox is null.

Upvotes: 0

Views: 687

Answers (2)

Andrew
Andrew

Reputation: 7880

Supposing your txtBox can be null (I guess it's a dynamically created control), you could do something like this:

bool isEmptyOrNull = txtBox == null || string.IsNullOrWhiteSpace(txtBox.Text)

Upvotes: 1

Dave Bish
Dave Bish

Reputation: 19646

Not really - however, you could make a little extension if it would save you time:

public static class TextBoxExtensions
{
    public static bool IsEmpty(this TextBox textBox)
    {
        return string.IsNullOrWhiteSpace(null == textBox ? null : textBox.Text);
    }
}

usage:

if(TextBox1.IsEmpty())
{
    ....

Upvotes: 3

Related Questions