Jake
Jake

Reputation: 29

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. 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);

Upvotes: 2

Views: 1163

Answers (3)

KH S
KH S

Reputation: 444

Can you post some more code? You set int priceTotal = 0 before adding. Looks to me it resets the total always to 0 before you add something. 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.

Upvotes: 0

THE LIFE-TIME LEARNER
THE LIFE-TIME LEARNER

Reputation: 1522

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")

Upvotes: 4

Kjartan
Kjartan

Reputation: 19111

You are currently adding the values priceTotal and e.g. 10, but not storing the result of that operation:

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 + 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.

Upvotes: 2

Related Questions