[英]How do I Add to the Value of an Integer when a CheckBox is Checked?
I want value to be added to an integer (int priceTotal), when a Checkbox is checked.我希望在选中复选框时将值添加到 integer (int priceTotal)。 The exercise is for ordering a pizza in a webform.
该练习用于在网络表单中订购比萨饼。 I want to be able to add to the price total depending on which size is selected and what toppings.
我希望能够根据选择的尺寸和配料添加到总价格中。
int priceTotal = 0;
if (smallPizzaCheck.Checked)
{
priceTotal + 10;
}
else if (mediumPizzaCheck.Checked)
{
priceTotal + 13;
}
//Et cetera, et cetera
orderTotal.Text = Convert.ToString(priceTotal);
int priceTotal = 0;
if (smallPizzaCheck.Checked)
{
priceTotal = priceTotal + 10;
}
else if (mediumPizzaCheck.Checked)
{
priceTotal = priceTotal + 13;
}
//Et cetera, et cetera
orderTotal.Text = Convert.ToString(priceTotal);
Just try this....whenever check box checked...the price total added..again and again... so you can sum into (priceTotal value) and display into textbox name("orderTotal.Text")
只需尝试一下。...每当检查复选框时...添加的价格总数。
You are currently adding the values priceTotal
and eg 10
, but not storing the result of that operation:您当前正在添加值
priceTotal
和例如10
,但不存储该操作的结果:
if (smallPizzaCheck.Checked)
{
priceTotal + 10; // Will be new sum, but where are your keeping the result?
}
You should do this to update the value of priceTotal
:您应该这样做来更新
priceTotal
的值:
priceTotal = priceTotal + 10;
In a simple case like this however, there is a simplified syntax available:然而,在这样一个简单的情况下,有一个简化的语法可用:
priceTotal += 10; // Update priceTotal by adding the value on the right.
Note the +=
.注意
+=
。 This essetially means " add or combine whatever is to the right of the operator with the value to the left of the operator ".这本质上意味着“将运算符右侧的任何内容与运算符左侧的值相加或组合”。
Sidenote: I say whatever in stead of the number because this syntax also works for other cases like strings (concatenation) and events (adding subscribers / event listeners), although that is beyond the context of this question.
旁注:我说什么而不是数字,因为这种语法也适用于其他情况,如字符串(连接)和事件(添加订阅者/事件侦听器),尽管这超出了这个问题的范围。
Can you post some more code?您可以发布更多代码吗? You set int priceTotal = 0 before adding.
您在添加之前设置了 int priceTotal = 0。 Looks to me it resets the total always to 0 before you add something.
在我看来,在添加某些内容之前,它总是将总数重置为 0。 In a real live ordering system you would be able to add more than one pizza.
在真实的实时订购系统中,您可以添加多个披萨。
To to make sure you keep an exising total I would do it like that:为了确保您保持现有总数,我会这样做:
int priceTotal;
if (!string.IsNullOrEmpty(orderTotal.Text))
{
priceTotal = Convert.ToInt32(orderTotal.Text);
}
else
{
priceTotal = 0;
}
Then you can add to the current total.然后您可以添加到当前总数。 Hope this helps.
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.