【问题标题】:Not able to cast string to int. Error msg: Input string was not in a correct format无法将字符串转换为 int。错误消息:输入字符串的格式不正确
【发布时间】:2009-08-27 08:17:09
【问题描述】:

我有以下代码输出数字“40”:

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

然后我尝试将字符串转换为 int,我得到一个异常/错误:

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

这是我收到的错误消息:

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 

我不明白出了什么问题。我之前多次将castet string转换为int,从未发生过这个问题。

请帮忙:)

更新

我找到了解决办法。我不知道为什么会这样……但它确实有效……
我将转换放在 Try Catch 中,现在它可以工作了。想出一个: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);
}

【问题讨论】:

标签: c# .net


【解决方案1】:

我认为“输入字符串的格式不正确”这行说明了一切。在行中

 int i = Convert.ToInt32(str);

str 可能包含字母字符。调试的时候看看,里面有什么?

【讨论】:

  • 我正在使用 Visual Web Developer 2008,但无法进行调试:( 输入字符串仅包含数字 '40' 可能还有空格。因此我没有理解“格式不正确”的含义
  • "也许还有空白"
【解决方案2】:

我有同样的问题,但只有 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);
        }

【讨论】:

  • 同样的问题,只有 try catch 有效,检查了我能想到的所有可能的字符组合,换行符,空格...
【解决方案3】:

您应该将 Trim() 添加到您认为它失败的代码行中。这可能与过多的空间有关。

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

甚至可能检查str是否为string.Empty,这也会导致Convert.ToInt32崩溃。

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

【讨论】:

  • 字符串不为空,它包含数字'40'。也添加 Trim() dfoes 无济于事。
  • @Steven: Convert.ToInt32 如果字符串只包含两个字符“40”而不包含其他字符,则可以工作。
  • @Luke:通常是的。但在这种情况下,没有。查看我的解决方案。
  • @Steven:看起来您的“解决方案”只是将错误隐藏在try...catch 中,而不是阻止它。
【解决方案4】:

代码没问题,但是如果str可能有空格,那么你应该在转换之前删除它们:

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

【讨论】:

  • Addin Trim() 没有帮助。空白不是问题。
【解决方案5】:

这将是您尝试将 Null 或在这种情况下为“”(在您的 .ToString() 之后)转换为 int。

尝试为空值插入可接受的占位符,例如下面代码中显示的 -1。

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

【讨论】:

    【解决方案6】:

    原因也可能是注册表问题。见https://support.microsoft.com/en-us/help/942460/system-formatexception-occurs-when-attempting-to-convert-a-numeric-str

    他们解释说,如果值 HKEY_CURRENT_USER\Control Panel\International\sPositiveSign 包含错误内容,则正确的数字字符串可能仍无法转换。在我们这个世界的某些地方,这个键的值应该是空的(没有空格,只是空的)。

    可能这不是你的问题,但我在这里添加它是为了那些可能正是因为这个原因而导致问题的人......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-03
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多