9

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);
}
4
  • 2
    You're not casting string to int, you're converting. Commented Aug 27, 2009 at 8:25
  • Also spoken of as Casting ;o) blogs.msdn.com/csharpfaq/archive/2004/05/30/144652.aspx. I know propert casting is eg. (Int23)myString - but if that doesnt work, you either must pars or convert. Commented Aug 27, 2009 at 8:32
  • I think you should debug your app, try to use showmessage to see the str before converting. Commented Aug 27, 2009 at 9:29
  • This may be relevant: support.microsoft.com/kb/942460 Commented Mar 18, 2014 at 22:00

7 Answers 7

9

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?

Sign up to request clarification or add additional context in comments.

2 Comments

I'm using Visual Web Developer 2008 and I haven't been able to make the debugging work :( The input string only contains the number '40' and maybe white space. Therefor I don't understand what it merans by 'incorrect format'
"and maybe white space" <-- Then you better use str.Trim(), because if you maybe have white space then maybe that will crash the function.
4

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

1 Comment

Same problem, only a try catch works, checked for all possible combination of characters i can think of, newlines, spaces...
2

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

4 Comments

The string is not empty, it contains the number '40'. Also adding Trim() dfoes not help.
@Steven: Convert.ToInt32 will work if the string contains just the two characters "40" and nothing else.
@Luke: Normally yes. But in this case, no. See my solution.
@Steven: It looks like your "solution" is just burying the error in a try...catch, rather than preventing it.
1

The code is ok, but if the str may have white space, so you should remove them before convert:

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

1 Comment

Addin Trim() does not help. Whitespace is not the problem.
0

It will be that you are trying to convert Nulls or in this case "" (after your .ToString()) to an int.

Try something that will insert an acceptable placeholder for nulls such as -1 shown in the code below.

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

Comments

0

The cause might also be a registry problem. See https://support.microsoft.com/en-us/help/942460/system-formatexception-occurs-when-attempting-to-convert-a-numeric-str

They explain that a proper number string might still fail to convert if the value HKEY_CURRENT_USER\Control Panel\International\sPositiveSign contains something bad. In our parts of the world, the value for this key should be empty (no space, just empty).

Probably that was not your problem, but I'm adding it here for someone who might be having exactly this as the cause for their problem...

Comments

0

I found that the error was caused by having a comma in the number, so you can't convert "1,000" to INT, but "1000" is accepted.

1 Comment

If you have a new question, please ask it by clicking the Ask Question button. Include a link to this question if it helps provide context. - From Review

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.