Not able to cast string to int. Error msg: Input string was not in a correct format

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?


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

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";
}

Tags:

C#

.Net