2009-08-27 46 views
5

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

您不是將字符串轉換爲int,而是轉換。 –

+0

也稱爲鑄造; o)http://blogs.msdn.com/csharpfaq/archive/2004/05/30/144652.aspx。我知道屬性鑄造是例如。 (Int23)myString - 但如果這不起作用,您必須進行分析或轉換。 – Steven

+0

我認爲你應該調試你的應用程序,嘗試使用showmessage在轉換之前查看str。 –

回答

6

我覺得「輸入字符串的格式不正確」這一行解釋了這一切。在該行

int i = Convert.ToInt32(str); 

str可能包含字母字符。在調試時看看它,它包含什麼?

+0

我使用的是Visual Web Developer 2008,但我一直無法進行調試工作:(輸入字符串只包含數字'40',也許是空格,因此我不明白它'不正確的格式' – Steven

+8

「,也許空白空間」< - 然後你最好使用str.Trim(),因爲如果你可能有空白區域,那麼也許會崩潰的功能。 –

0

的代碼是好的,但如果海峽可能有空白,所以你應該在轉換前刪除它們:

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

Addin修剪()沒有幫助。空白不是問題 – Steven

1

您應該添加TRIM()到您的代碼行,你認爲失敗。這可能與過多的空間有關。

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

甚至檢查,看看是否STR的String.Empty,這也將導致Convert.ToInt32崩潰。

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

字符串不是空的,它包含數字'40'。並且添加Trim()dfoes沒有幫助。 – Steven

+1

@Steven:'Convert.ToInt32 * * *將工作,如果字符串只包含兩個字符「40」,沒有別的, – LukeH

+0

@Luke:通常是的,但在這種情況下,不,看到我的解決方案 – Steven

3

我有同樣的問題,而只是一門心思抓方法解決我的問題

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

同樣的問題,只有一個try catch工程,檢查所有可能的字符組合,我可以想到的,換行符,空格... – bonitzenator

0

這將是你正試圖轉換空值或在這種情況下,「」(後您的.ToString())到INT。

嘗試插入一個可接受的佔位符,例如下面代碼中顯示的-1。

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