简体   繁体   中英

How to sum all numbers in a Listbox using TextBox?

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();
}

Sorry for maybe not answer but it is strange that your compiler didn't tell you to initialize sum. The second I tested your code and it works correctly as expected that means that if the problem is not in sum variable then you made something else to this fields somewhere else so your code doesn't work correctly.

Having in mind your comment to previous person I'd say the same. In some cases (I know it's funny but) you may have viruses on your computer. Check it. Once in my life I've failed my maths lab work because of virus that interrupted my program so it drew the wrong chart !sick I know :D

    private void button1_Click(object sender, EventArgs e)
    {
        var sum = 0;
        var value = 0;

        listBox1.Items.Add(textBox1.Text);

        foreach (var item in listBox1.Items)
        {
            if (!int.TryParse(item.ToString(), out value))
                continue;

            sum = sum + value;
        }

        label1.Text = sum.ToString();
        textBox1.Text = string.Empty;
    }

Use of unassigned local variable 'sum', sum must be assigned before use !

decimal sum = 0;

Rest all is ok

Need to set sum to 0 and also it is probably best to use a foreach instead of a Dotloop.

private void AddButton_Click(object sender, EventArgs e) {
    decimal sum = 0;
    listBox2.Items.Add(TextBox1.Text);
    TextBox1.Text = ""; 
    foreach (string s in listBox2) { 
        sum += Convert.ToDecimal(s);
    } 
    Label1.Text = sum.ToString(); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM