【发布时间】: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);
}
【问题讨论】:
-
您不是在将字符串转换为 int,而是在转换。
-
也称为 Casting ;o) blogs.msdn.com/csharpfaq/archive/2004/05/30/144652.aspx。我知道属性铸造是例如。 (Int23)myString - 但如果这不起作用,您必须解析或转换。
-
我认为你应该调试你的应用程序,在转换之前尝试使用 showmessage 来查看 str。
-
这可能是相关的:support.microsoft.com/kb/942460