Check Whether a TextBox is empty or not

user5683768 picture user5683768 · Dec 15, 2015 · Viewed 74.1k times · Source

I have a TextBox. And I want to check if it's empty.

Which way is better

if(TextBox.Text.Length == 0)

or

if(TextBox.Text == '')

?

Answer

Fᴀʀʜᴀɴ Aɴᴀᴍ picture Fᴀʀʜᴀɴ Aɴᴀᴍ · Dec 15, 2015

You should use String.IsNullOrEmpty() to make sure it is neither empty nor null (somehow):

if (String.IsNullOrEmpty(textBox1.Text))
{
    // Do something...
}

More examples here.

For practical purposes you might also consider using String.IsNullOrWhitespace() since a TextBox expecting whitespace as input probably negates any purpose, except in case of, say, letting the user pick a custom separator for stuff.