Shaku
Shaku

Reputation: 13

C# Need Help on Converting String to Int?

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.

Upvotes: 1

Views: 295

Answers (4)

Carlos Quintanilla
Carlos Quintanilla

Reputation: 13343

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.

Upvotes: 0

ppiotrowicz
ppiotrowicz

Reputation: 4614

private void textBox1_TextChanged(object sender, EventArgs e)
{
    var minusTime;
    if (textBox1.Text != null && int.TryParse(textBox1.Text, out minusTime))
    {
    }
    else
    {
        minusTime = 0;
    }
}

Upvotes: 1

CB.
CB.

Reputation: 60976

Try using:

minusTime = Int32.Parse(textBox1.Text); 

Upvotes: 2

ChrisF
ChrisF

Reputation: 137188

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.

Upvotes: 4

Related Questions