954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

IF condition as presence check?

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

ppatryk
Newbie Poster
7 posts since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

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!
}
Mitja Bonca
Nearly a Posting Maven
2,485 posts since May 2009
Reputation Points: 641
Solved Threads: 474
 

Thats great, thanks for the help.

ppatryk
Newbie Poster
7 posts since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

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

Mitja Bonca
Nearly a Posting Maven
2,485 posts since May 2009
Reputation Points: 641
Solved Threads: 474
 
if(textBox.Text != String.Empty)
{
   //not empty (not null, even empty and null are not the same things)
}
else
{
   //empty!
}

See also: <a href="http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx">String.IsNullOrEmpty</a> , <a href="http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx">String.IsNullOrWhiteSpace</a> ; depending on what your needs are.

For example:

if(String.IsNullOrWhiteSpace(textBox1.Text))
{
    ...
}
gusano79
Posting Pro
521 posts since May 2004
Reputation Points: 182
Solved Threads: 77
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: