我试图从列表框中将项目添加到组合框后计算项目的总价格。在列表框中,我有项目类型和ts价格。当我将每个项目(单击addButton)添加到组合框时,我希望看到总价格增加。但我所看到的是该项目被添加到组合框但我只看到单个项目价格而不是价格的总和。这是我的代码示例。
private void addButton_Click(object sender, EventArgs e)
{
decimal price; // variables to holds the price
decimal total = 0; // variables to hold the total
int counter;
for (counter=0; counter <= 5; counter++)
{
price = decimal.Parse(priceLabel2.Text);
// add items price
total += price;
// display the total amount
costLabel.Text = total.ToString("c");
}
任何帮助将不胜感激,
答案 0 :(得分:4)
变化:
private void addButton_Click(object sender, EventArgs e)
{
decimal price; // variables to holds the price
decimal total = 0; // variables to hold the total
int counter;
for (counter=0; counter <= 5; counter++)
{
price = decimal.Parse(priceLabel2.Text);
// add items price
total += price;
// display the total amount
costLabel.Text = total.ToString("c");
}
为:
decimal total = 0; // variables to hold the total
private void addButton_Click(object sender, EventArgs e)
{
decimal price; // variables to holds the price
int counter;
for (counter = 0; counter <= 5; counter++)
{
price = decimal.Parse(priceLabel2.Text);
// add items price
total += price;
// display the total amount
costLabel.Text = total.ToString("c");
}
}
这里的重要变化是将总变量移到函数之外。这意味着在点击之间保持该值。如果你把它放在函数中,它会在每次点击时重置为0(这不是你想要的)。