我havethe以下,輸出數字「40」代碼:無法將字符串轉換爲int。錯誤信息:輸入字符串的不正確的格式
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
我不明白什麼是錯的。我以前曾經多次將int串聯到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,而是轉換。 –
也稱爲鑄造; o)http://blogs.msdn.com/csharpfaq/archive/2004/05/30/144652.aspx。我知道屬性鑄造是例如。 (Int23)myString - 但如果這不起作用,您必須進行分析或轉換。 – Steven
我認爲你應該調試你的應用程序,嘗試使用showmessage在轉換之前查看str。 –