Reputation: 13
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.
Upvotes: 1
Views: 429
Reputation: 258
Also you can use linq to achieve it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var result = from num in this.checkedListBox1.CheckedItems.OfType<string>()
select Convert.ToInt32(num);
this.textBox1.Text = result.Sum().ToString();
}
}
}
Upvotes: 0
Reputation: 13887
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.
Upvotes: 2