1

So... I have this section of code here, everything seems perfect but when I try to run this, it gives a formatting exception handler error.

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (textBox1.Text != null)
        {
            minusTime = Convert.ToInt32(textBox1.Text); // fix this... idk what's even wrong. Just trying to assign user input to minusTime...
        }
        else
        {
            minusTime = 0;
        }
    }

*Note: textbox1 is user input of an integer value. minusTime is a null integer that is to be assigned to the user input.

I've tried running this with just "Convert.ToInt32(textBox1.Text)" but it still gives me an exception saying the user inputted a wrong format... when the user input is clearly an int.

4 Answers 4

4

You want

bool result = Int32.TryParse(textBox1.Text, out minusTime);

This will cope if the input isn't an integer returning false.

MSDN page

There is another overload that takes in more information about the possible format of the number:

public static bool TryParse(
    string s,
    NumberStyles style,
    IFormatProvider provider,
    out int result
    )

This will cope with currency symbols etc.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This worked perfectly! Thanks for getting rid of my headache, haha!
2

Try using:

minusTime = Int32.Parse(textBox1.Text); 

3 Comments

Also, change this line to if (!string.IsNullOrEmpty(textBox1.Text))
Int32.TryParse is another similar solution
Thanks! This worked out great too! This is much simpler than what I was banging my head over...
1
private void textBox1_TextChanged(object sender, EventArgs e)
{
    var minusTime;
    if (textBox1.Text != null && int.TryParse(textBox1.Text, out minusTime))
    {
    }
    else
    {
        minusTime = 0;
    }
}

Comments

0

You can use:

int minusTime=0;
Int32.TryParse(textBox1.Text, out minusTime);

minusTime will be 0 if textBox1.Text is not integer or even if it is null.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.