I want to count and sum all values in a ListBox
. For example, I have the following values in my ListBox
: 4
, 6
, 1
, 7
. My current value is 18
. If I add a 2
with a TextBox
, I need to get 20
and if I add 5
I need to get 25
in total.
If I try it with the below code, it gives me a whole other number.
Here is my code:
private void AddButton_Click(object sender, EventArgs e)
{
decimal sum;
listBox2.Items.Add(TextBox1.Text);
TextBox1.Text = "";
for (int i = 0; i < listBox2.Items.Count; i++)
{
sum += Convert.ToDecimal(listBox2.Items[i].ToString());
}
Label1.Text = sum.ToString();
}
You missed to initialize default value of sum. Assign sum = 0
before adding values to sum
variable
private void AddButton_Click(object sender, EventArgs e)
{
decimal sum = 0; //Set sum = 0 by default
listBox2.Items.Add(TextBox1.Text);
TextBox1.Text = "";
for (int i = 0; i < listBox2.Items.Count; i++)
{
//To check value of sum after each iteration, you can print it on console
Console.WriteLine("Sum =" +sum);
sum += Convert.ToDecimal(listBox2.Items[i].ToString());
}
Label1.Text = sum.ToString();
}