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?
Your problem is here:
You’re checking the length of one text box and setting the text of another. Change it to this:
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.