Search code examples
c#listboxsumcheckedlistbox

checkedlistbox addition with other numbers


It's my first post. I'm trying to make multiple sums in a checkedlistbox in Visual C#. There are 108 numbers, one in each row, and I'm trying to sum the checked item(s) with each one of the rest and print it in a textbox.

I have done this, but I think it's incorrect. This actually does the sum, but also with the number itself and the whole thing 108 times

I want to add the checked number with the rest numbers in the checkbox.

private void button2_Click(object sender, EventArgs e)
{
   foreach(string checkednumber in checkedlistbox1.CheckedItems)
   {
      double x = Convert.ToDouble(checkednumber);

      double a = 0;
      for (double y = 0; y < checkedlistbox1.Items.Count; ++y)
      {
         foreach (string othernumbers in checkedlistbox1.Items)
         {
            double z = Convert.ToDouble(othernumbers);
            sum = x + z;
            string str = Convert.ToString(sum);
            listbox1.Items.Add(str);
         }
      }
   }  
}

Thanks for any help.


Solution

  • You just want to sum the numbers for items that are checked?

    double sum = 0;
    
    foreach(object checkedItem in checkedlistbox1.CheckedItems)
    {
        try 
        {
            sum += Convert.ToDouble(checkedItem.ToString()); 
        }
        catch (FormatException e) {} //catch exception where checkedItem is not a number
    
        listbox1.Items.Add(sum.ToString());
    } 
    

    Your question is incredibly unclear, I'm not really sure if this is what you want at all.