Unable to pass string to int. Msg error: input line was not in the correct format

I have the following code that 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 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 happened. I have already imposed a string on an int several times, and this problem never occurred.

Please, help:)

Update

I have found a solution. I have no idea why this works ... but it works ...
I put the conversion inside Try Catch, and now it works. The figure shows that one of them: 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);
}
+5
source share
6 answers

, " " .

 int i = Convert.ToInt32(str);

str . , ?

+6

, try catch

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

Trim() , , , . , .

int i = Convert.ToInt32(str.Trim());

, , str str.Empty, Convert.ToInt32.

if (string.IsNullOrEmpty(str)) {
    str = "0";
}
+2

, str , :

int i = Convert.ToInt32(str.Replace(" " ,""));  // <-- This is where it fails I t hink. But why??
0

, Nulls "" ( .ToString()) int.

-, , -1, .

Convert.ToInt32(newHotel["numAllergyRooms"].ToString().Trim() == "" ? "-1" : newHotel["numAllergyRooms"].ToString().Trim());
0

. . Https://support.microsoft.com/en-us/help/942460/system-formatexception-occurs-when-attempting-to-convert-a-numeric-str

They explain that the correct number string may still not be converted if the value of HKEY_CURRENT_USER \ Control Panel \ International \ sPositiveSign contains something bad. In our parts of the world, the value of this key should be empty (no space, just empty).

It may not have been your problem, but I am adding it here for someone who might have just that as the cause of their problem ...

0
source

All Articles