'Adding 2 listbox and the sum display at the label
I would like to ask how to add two listbox and the sum is in the label:
When i check the first listbox it sum but when i checked the other checkbox the label resets to 0 and summing up other numbers in the 2nd listbox i checked
My code on first listbox:
protected void add(object sender, EventArgs e)
{
int sum = 0;
int test = Int32.Parse(lbl_.Text);
for (int j = 0; j <= pizzalist.Items.Count - 1; j++)
{
if (pizzalist.Items[j].Selected)
{
test += Convert.ToInt32(pizzalist.Items[j].Value);
}
}
lbl_.Text = test.ToString();
My 2nd code in other listbox:
protected void Button5_Click(object sender, EventArgs e)
{
int sum = 0;
// for (int j = 0; j <= waterlist.Items.Count - 1; j++)
for (int j = 0; j <= waterlist.Items.Count -1; j++)
{
if (waterlist.Items[j].Selected)
{
sum += Convert.ToInt32(waterlist.Items[j].Value);
}
}
lbl_.Text = sum.ToString();
}
Solution 1:[1]
Few things:
- you need to read the label in second function and add the sum variable to make it work as expected - now you are changing the label without checking what value it has; more: you can try to make global variable with sum of items
- use TryParse, or at least Parse with try-catch, Convert is a weak idea
- try to use foreach instead of for
- you can even use Linq to quickly sum selected items
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pbies |
