0

I'm making a Windows Form Application with C#.

One of my forms contains 5 group boxes, each containing 6 checkboxes inside. I need to count all the checked checkboxes.

At the moment I have coded it as follows:

int NumOfRacks1 = groupBoxPace.Controls.OfType<CheckBox>() .Count(cb => cb.Checked);

However I would have to repeat the above 5 times and then add all the variables together to get an answer. I'm sure there is a smarter way to do this which cuts down the code.

I tried to combine three of them as follows:

var allRacks = groupBoxSamsung.Controls.OfType<CheckBox>().Concat(groupBoxPace.Controls.OfType<CheckBox>().Concat(groupBox780.Controls.OfType<CheckBox>()));

But this didn't work as expected.

Does anyone know of a way to achieve this?

John Saunders
  • 160,644
  • 26
  • 247
  • 397

2 Answers2

0

I need to count all the checked checkboxes.

Is not working because you're not counting. Try this.

var items = (groupBox1.Controls.OfType<CheckBox>()
    .Concat(groupBox2.Controls.OfType<CheckBox>()))
    .Where(ch => ch.Checked == true).Count();

There you have your count.

Erre Efe
  • 15,387
  • 10
  • 45
  • 77
0

I found a question on StackOverflow How to get all childControls of a type on a form and extended it to count the checked elements.

private void button1_Click(object sender, EventArgs e)
{
    label1.Text = (from c in GetAll(this, typeof(CheckBox))
                    where (c as CheckBox).Checked
                    select c).Count().ToString();                    
}
// credits go to @PsychoCoder for this part
public IEnumerable<Control> GetAll(Control control, Type type)
{
    var controls = control.Controls.Cast<Control>();
    return controls.SelectMany(ctrl => GetAll(ctrl, type))
                                .Concat(controls)
                                .Where(c => c.GetType() == type);
}

In general I think this snippet should do the trick and you don't have to concat all groupBoxes!

EDIT

Adapted to count all checked checkBoxes on your form, no matter if checkboxes are childControls or not.

Type type = typeof(CheckBox);
var controls = this.Controls.Cast<Control>();
label1.Text = controls.SelectMany(ctrl => GetAll(ctrl))
                            .Concat(controls)
                            .Where(c => c.GetType() == type && (c as CheckBox).Checked)
                            .Count().ToString();
Community
  • 1
  • 1
Pilgerstorfer Franz
  • 8,303
  • 3
  • 41
  • 54