erwin mendoza
erwin mendoza

Reputation: 15

don't know how to convert properly

int a = Convert.ToInt32(subjectsLabel1.Text);
int b = int.Parse(internetLabel1.Text);
int total = a+b;
label1.Text = total.ToString();

the error "Input string was not in a correct format." keeps poping out. I tried to convert using the "int.parse" and the "convert.toint32" syntax but the same error keeps showing up.

*the values in the subjectsLabel1 and internetlabel1 would be coming from the database (which was done in visual studio) w/ datatype varchar(10).

Upvotes: 0

Views: 102

Answers (3)

bilash.saha
bilash.saha

Reputation: 7316

You Cannot convert to Int32 if the string contains a decimal pointor its not a valid integer .Check

string test = "15.00"
int testasint = Convert.ToInt32(test); //THIS WILL FAIL!!!

Because Int32 does not support decimals. If you need to use decimals, use Float or Double.

So in this situation you can use

int.TryParse 

also

Upvotes: 0

Wouter de Kort
Wouter de Kort

Reputation: 39898

If you're not sure the user is giving you a legal Int32 value to convert you can use:

int result;

if (!int.TryParse(subjectsLabel.Text, out result))
{
 ShowAMessageToTheUser();
}
else
{
 UseResult();
}

Using TryParse won't trow an exception when you try to parse a string. Instead it will return false and the out parameter is not valid to use.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

There is nothing wrong with the way you are parsing those string values to integers. It's just that their value doesn't represent a valid integer so it cannot be parsed and an exception is thrown. You could use the int.TryParse method to handle gracefully this case:

int a;
int b;
if (!int.TryParse(subjectsLabel1.Text, out a))
{
    MessageBox.Show("please enter a valid integer in subjectsLabel1");
} 
else if (!int.TryParse(internetLabel1.Text, out b))
{
    MessageBox.Show("please enter a valid integer in internetLabel1");
}
else
{
    // the parsing went fine => we could safely use the a and b variables here
    int total = a + b;
    label1.Text = total.ToString();
}

Upvotes: 3

Related Questions