Not able to cast string to int. Error msg: Input string was not in a correct format
Solution 1:
I think the line "Input string was not in a correct format" explains it all. In the line
int i = Convert.ToInt32(str);
str might be containing alphabetic characters. Take a look at it while debugging, what does it contain?
Solution 2:
I had the same problem but only try catch method solved my problem
try
{
decimal dPrice=Convert.ToDecimal(sPrice);
decimal dFreight = Convert.ToDecimal(sFreight);
decimal dLocalship = Convert.ToDecimal(sLocalship);
decimal dTarrif = Convert.ToDecimal(sTarrif);
decimal dBenefit = Convert.ToDecimal(sBenefit);
decimal dTax = Convert.ToDecimal(sTax);
decimal dVat = Convert.ToDecimal(sVat);
decimal dConv = Convert.ToDecimal(sConv);
decimal factors=(dTarrif+dBenefit+dTax+dVat)/100+1;
decimal dTotal=(dPrice+dFreight)*dConv;
dTotal=dTotal*factors;
string st = Convert.ToString(dTotal);
e.Row.Cells[iCell].Text = "price is: " + st + " Rials";
}
catch(Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
Solution 3:
You should add Trim() to your code-line where you think it fails. It probably has to do with excessive spaces.
int i = Convert.ToInt32(str.Trim());
Maybe even check to see if str is string.Empty, this will also cause Convert.ToInt32 to crash.
if (string.IsNullOrEmpty(str)) {
str = "0";
}