2013-08-27 22 views
1
 if (Session["totalCost"] != null) 
     { 
      if (Session["totalCost"] != "confirm") 
      { 
       totRevenueLabel.Text = totalRevenueInteger.ToString(); 
       totalRevenueInteger += int.Parse(Session["totalCost"].ToString()); 
      } 

然而,當我執行的程序,它說輸入字符串沒有把正確的格式輸入字符串並沒有把正確的格式

請幫助!

+1

它抱怨哪一行? 'Session [「totalCost」]的值不是「確認」,但它的價值是什麼? –

+0

totalRevenueInteger + = int.Parse(Session [「totalCost」]。ToString()); –

+0

如果你在該行上放置一個斷點,它的值是什麼? –

回答

1

該錯誤表示您嘗試從中解析整數的字符串實際上並不包含有效整數。

int i; 
if(int.TryParse(Session["totalCost"].ToString(), out i) 
{ 
    totalRevenueInteger = i; 
} 
+0

所以我該怎麼做,請幫助! –

+0

你應該打印出Session [「totalCost」],然後想一想爲什麼這個值不是一個整數。一旦你解決了這個問題,使得值是一個整數,在你的代碼中放置一些檢查邏輯,這樣你就不會再次遇到這個問題。 – Kye

1

如果Session["totalCost"].ToString())爲空或空int.parse將拋出input string was not put correct format

嘗試添加錯誤處理或使用int.TryParse和鄧賢蘭默認值

例子:

  if (Session["totalCost"] != "confirm") 
     { 
      totRevenueLabel.Text = totalRevenueInteger.ToString(); 

      int value = 0; 
      int.TryParse(Session["totalCost"].ToString(), out value); 

      totalRevenueInteger += value; 
     } 

  if (Session["totalCost"] != "confirm") 
     { 
      totRevenueLabel.Text = totalRevenueInteger.ToString(); 

      string value = Session["totalCost"].ToString(); 

      totalRevenueInteger += !string.IsNullOrEmpty(value) ? int.TryParse(value) : 0; 
     } 
+0

我仍然需要Session [「....」!= null在頂部?謝謝 –

+0

我得到它的作品,但它每次添加60,我按下按鈕:( –

+0

從代碼,我們可以看到,這是因爲'會議[「totalCost」]'具有60的值。如果它不是,那麼你 –

2

你正在分析

int.Parse(Session["totalCost"].ToString()); 

所以假設Session["totalCost"]在一個字符串格式的數值。但早期的你正在做的:

if (Session["totalCost"] != "confirm") 

這表明Session["totalCost"]包含字符串格式的字母。兩種說法都相反。我希望現在你可以找到你的問題。

+0

我認爲代碼暗示如果'[「totalCost」]'不等於'confirm',那麼它就是一個數字,所以這個邏輯對我來說似乎很好,只要在解析之前有一個額外的檢查。 –