문제

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:

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.

다른 팁

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));

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top