Click here to Skip to main content
15,886,519 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Ok, so im creating a window that basically inserts the data entered into a SQL database..

But its probably a simple error im making here.. But for some reason when i leave a textbox blank, it still says that it has an incorrent string input.

here is the if statement of which checks it has a null value or not.

C#
if (quantityAvailableTextBox.Text != null)
{ p.QuantityAvailable = Convert.ToInt32(quantityAvailableTextBox.Text); }
else { }


Why is this happen, again, im sure its a simply solution... But for some reason, because of the fact that the textbox.text is null it should skip and go straight to the else... but instead it goes through the if code.
Posted
Comments
[no name] 11-May-14 16:55pm    
You should be using string.IsNullOrWhitespace() instead of just checking for null, which I do not believe that it ever would be.
[no name] 11-May-14 17:01pm    
Thank you my friend, I knew it was something simple 😂😂
[no name] 11-May-14 17:11pm    
You're welcome. For added safety I would used Int32.TryParse instead of the convert.
[no name] 11-May-14 17:17pm    
Thank you:) but how come? What's the benefits of using that? How is it safer? I'm asking in a pupil asking his teach kind of way 😂😂
[no name] 11-May-14 17:19pm    
TryParse returns a bool for success/failure. If the conversion fails, it does not throw an exception. Convert throws an exception.

1 solution

Use IsNullOrEmpty[^]

C#
if (!string.IsNullOrEmpty(quantityAvailableTextBox.Text))
{
    p.QuantityAvailable = Convert.ToInt32(quantityAvailableTextBox.Text);
}
else { }
 
Share this answer
 
v2
Comments
[no name] 11-May-14 18:46pm    
Or IsNullOrWhitespace depending on his version of the framework :-)
Manas Bhardwaj 12-May-14 3:38am    
Yeah, old habits die hard. Thanks :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900