0

I have made this small application for employee salary calculation. I have added a checked list box where user can tick multiple checkboxes for choosing benefits. The program will check all the items checked and will add the values tick. How should i do this? So far I tried this but it doesn't work

    private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int Sum = 0;

        for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++)
        {

            foreach (var item in checkedListBox1.)
            {
                Sum = Sum + Int32.Parse(checkedListBox1.CheckedItems.ToString());
            }
        }
        //textBox5.Text = Convert.ToString(Sum);
    }
JensG
  • 13,148
  • 4
  • 45
  • 55
user3132148
  • 5
  • 1
  • 9

2 Answers2

2

You can use LINQ for that:

 var sum = checkedListBox1.CheckedItems.OfType<object>()
           .Sum(x => int.Parse(x.ToString()));

Or change your for loop to foreach:

int Sum = 0;

foreach (var item in checkedListBox1.CheckedItems)
{
    int result;
    if(int.TryParse(item.ToString(), out result))
            Sum += result;
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0

to make it short

        int result = 0;
        foreach (var seleted in checkedListBox1.CheckedItems)
        {
           result += int.Parse(seleted.ToString());
        }
Angelo
  • 335
  • 4
  • 10