Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

I havethe following code which outputs the number '40':

Hashtable ht = new Hashtable();
ht.Add("numRooms", pageData.Property["romtotalt"].ToString());
string str = ht["numRooms"].ToString();
lblMigrate.Text = i.ToString();

Then I try to convert the string to an int, and I get an exception / error:

Hashtable ht = new Hashtable();
ht.Add("numRooms", pageData.Property["romtotalt"].ToString());
string str = ht["numRooms"].ToString();
int i = Convert.ToInt32(str);  // <-- This is where it fails I t hink. But why??
lblMigrate.Text = i.ToString();

This is the error message I get:

Server Error in '/' Application.
Input string was not in a correct format.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: Input string was not in a correct format.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[FormatException: Input string was not in a correct format.]
   System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) +7469351
   System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) +119
   development.templates.HotellGuide.btnMigrateHotels_Click(Object sender, EventArgs e) +956
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565


Version Information: Microsoft .NET Framework Version:2.0.50727.3082; ASP.NET Version:2.0.50727.3082 

I don't understand what's wrong. I'va castet string to int multiple times before, and never has this problem occured.

Please help :)

Update

I have found a solution. I have NO idea why this works.... but it works...
I put the convertion inside a Try Catch, and now it works. Figure that one out :op

int numRooms = 0;
int numAllergyRooms = 0;

try
{
    numRooms = Convert.ToInt32(newHotel["numRooms"].ToString().Trim());
    numAllergyRooms = Convert.ToInt32(newHotel["numAllergyRooms"].ToString().Trim());
}
catch (Exception ex)
{
    Console.WriteLine("{0} Exception caught.", ex);
}
like image 467
Steven Avatar asked Aug 27 '09 08:08

Steven


People also ask

How do I fix resolve input string is not in a correct format error?

Input string was not in a correct format error occurs when you convert non-numeric data into an int or exceed the limit of the int data type. You should use Int. TryParse instead of Int32. Parse method to get rid of the said error.

What does input string mean?

n a device, such as a keyboard, used to insert data directly into a computerized system. input device. n (Computing) a peripheral device that accepts data and feeds it into a computer.


2 Answers

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?

like image 96
erelender Avatar answered Oct 23 '22 02:10

erelender


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);
        }
like image 43
Mohammad Motaghi Avatar answered Oct 23 '22 00:10

Mohammad Motaghi