2013-02-04 29 views
-2
public void button1_Click(object sender, EventArgs e) 
{ 
    if (cushioncheckBox.Checked) 
    { 
     decimal totalamtforcushion = 0m; 

     totalamtforcushion = 63m * cushionupDown.Value; 
     string cu = totalamtforcushion.ToString("C"); 
     cushioncheckBox.Checked = false; 
     cushionupDown.Value = 0; 
    } 

    if (cesarbeefcheckBox.Checked) 
    { 
     decimal totalamtforcesarbeef = 0m; 
     totalamtforcesarbeef = 1.9m * cesarbeefupDown.Value; 
     string cb = totalamtforcesarbeef.ToString("C"); 
     cesarbeefcheckBox.Checked = false; 
     cesarbeefupDown.Value = 0; 

    } 
} 

所以我有這些代碼。我如何將兩個字符串cb和cu加在一起?我試過如何將字符串添加到一起?

decimal totalprice; 
totalprice = cu + cb; 

但它說名稱在上下文中不存在。 我該怎麼辦?

我使用Windows形成順便說一句

+3

爲什麼你使用字符串變量,如果你執行數學? – Derek

+2

在你的'if'語句之外聲明你的字符串。和字符串!=小數,你將需要轉換它們。 – PhoenixReborn

+0

,因爲我想把總值放在文本框中! – user2037510

回答

2

你有幾個問題在這裏:

首先,你string cuif範圍內聲明。它不會超出這個範圍。如果您需要在if範圍之外使用它,請在外部聲明。

其次,數學運算不能應用於string s。你爲什麼將數字值轉換爲字符串?你的代碼應該是:

decimal totalamtforcushion = 0m; 

if (cushioncheckBox.Checked) 
{ 
    totalamtforcushion = 63m * cushionupDown.Value; 
    //string cu = totalamtforcushion.ToString("C"); You don't need this 
    cushioncheckBox.Checked = false; 
    cushionupDown.Value = 0; 
} 

decimal totalamtforcesarbeef = 0m; 
if (cesarbeefcheckBox.Checked) 
{ 
    totalamtforcesarbeef = 1.9m * cesarbeefupDown.Value; 
    //string cb = totalamtforcesarbeef.ToString("C"); you don't need this either 
    cesarbeefcheckBox.Checked = false; 
    cesarbeefupDown.Value = 0; 

} 

var totalprice = totalamtforcushion + totalamtforcesarbeef; 
+0

隨着這個答案,你需要了解顯示你的數字字符串,看看這個MSDN頁面,它會幫助你。 http://msdn.microsoft.com/en-gb/library/system.string.format.aspx – Derek

+0

只是爲了明確,因爲這似乎是一個新手問題。在這種情況下,var關鍵字評估爲小數。如果您感到困惑,請查看:http://msdn.microsoft.com/en-us/library/bb383973.aspx。然後,您可以像以前一樣使用totalprice.ToString(「C」)來獲取字符串表單。如果您願意,您也可以將總價格作爲小數點,它的結果完全相同。 – Gray

+0

string result = totalprice.ToString(「f2」);將給你的2位小數位。或simplerm totalamttextBox.Text = totalprice.ToString(「f2」); – Derek

0

一般情況下,「增加」兩個字符串(如你真的想找到兩個數字的總和):

  1. 轉換你的兩個字符串數字。
  2. 添加數字。
  3. 將總和轉換爲字符串。

非常簡單;但隨時問問你是否還有其他問題。