Hi, is it ok to use an if condition as a presence check, this is my code -

if (textBox1 != null)
            {
                MessageBox.Show("Dont Leave Blank");
     
            }

            else

                MessageBox.Show("Successfully added");

my code runs however no matter if there is text in textbox1 or if its left empty it shows "Dont Leave Blank" any suggestions?

thanks

Recommended Answers

Wrong. You have to put a property of a textbox control on the end of it to check it:

if(textBox.Text != String.Empty)
{
   //not empty (not null, even empty and null are not the same things)
}
else
{
   //empty!
}
Jump to Post

All 4 Replies

Wrong. You have to put a property of a textbox control on the end of it to check it:

if(textBox.Text != String.Empty)
{
   //not empty (not null, even empty and null are not the same things)
}
else
{
   //empty!
}

Thats great, thanks for the help.

No problem. Just thread as answered (or vote as useful), to close the thread.
bye

if(textBox.Text != String.Empty)
{
//not empty (not null, even empty and null are not the same things)
}
else
{
//empty!

See also: String.IsNullOrEmpty or String.IsNullOrWhiteSpace; depending on what your needs are.

if(String.IsNullOrWhiteSpace(textBox1.Text))
{
    ...
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.