-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 表单顺便说一句

4

2 回答 2

2

您在这里有几个问题:

首先,您string cuif范围内声明。它不会存在于该范围之外。如果需要在 的范围之外使用,请在外面if声明。

其次,数学运算不能应用于strings。为什么要将数值转换为字符串?您的代码应该是:

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;
于 2013-02-04T15:59:07.280 回答
0

通常,要“添加”两个字符串(您实际上是在尝试查找两个数字的总和):

  1. 将您的两个字符串转换为数字。
  2. 添加数字。
  3. 将总和转换为字符串。

很简单;但如果您有任何其他问题,请随时询问。

于 2013-02-04T15:58:46.733 回答