Cannot Convert Zero to int32 from textbox
-
23-09-2019 - |
Question
I have the following code to do a some very simple validation for a textbox
if(txtInStock.Text.Length == 0)
txtInStock.Text = Convert.ToString(0);
if (txtInStock.Text.Length == 0)
txtOnOrder.Text = Convert.ToString(0);
int inStockAmt = Convert.ToInt32(txtInStock.Text);
int onOrderAmt = Convert.ToInt32(txtOnOrder.Text);
This works fine when Text != 0 , but when Text == 0 I get a FormatException saying the string is not of the proper format. How can I correct this?
Solution
Your problem is here:
if (txtInStock.Text.Length == 0)
txtOnOrder.Text = Convert.ToString(0);
You're checking the length of one text box and setting the text of another. Change it to this:
if (txtOnOrder.Text.Length == 0)
txtOnOrder.Text = Convert.ToString(0);
Also, is there a reason you're using Convert.ToString(0)
instead of just "0"
? I don't particularly recommend using this approach for data validation, but this should correct the problem.
OTHER TIPS
As you can't be sure the user of your textbox will write a correct integer, I would recommend to use Int32.TryParse() instead of Convert.ToInt32. Thus, you'll be able to easily handle the error cases.
Would this code do?
if(txtInStock.Text.Length == 0) txtInStock.Text = "0"; if (txtInStock.Text.Length == 0) txtOnOrder.Text = "0"; int inStockAmt = Convert.ToInt32(txtInStock.Text); int onOrderAmt = Convert.ToInt32(txtOnOrder.Text);
Hope this helps, Best regards, Tom.
This is a simple way to handle an empty textbox
if( string.IsNullOrEmpty( txtInStock.Text ))
txtInStock.Text = "0";
if( string.IsNullOrEmpty( txtOnOrder.Text ))
txtOnOrder.Text = "0";
int inStockAmt = Convert.ToInt32(txtInStock.Text);
int onOrderAmt = Convert.ToInt32(txtOnOrder.Text);
I would also save the textbox values to temp variables and then do the comparisions unless if you wanted to force a 0 in the textbox when it is empty.
int inStockAmt = Convert.ToInt32(string.IsNullOrEmpty(txtInStock.Text) ? 0 : int.Parse(txtInStock.Text));