-4
private void button3_Click(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                count++;
            }
            if (checkBox2.Checked)
            {
                count++;
            }
            if (checkBox3.Checked)
            {
                count++;
            }
            if (checkBox4.Checked)
            {
                count++;
            }
            if (checkBox5.Checked)
            {
                count++;
            }
            MessageBox.Show($"{count}");
  • 1. Write a function. 2. Inside that function, check a checkbox's state. If its checked, increment a counter. 3. Repeat for each checkbox. 4. You have your result –  Apr 16 '21 at 14:08
  • Maybe if you include some of your code, and a good-faith attempt at this, then we would be happy to help further. –  Apr 16 '21 at 14:09
  • @Amy excuse me i'm not used to Stackoverflow yet hahaha I edited and posted part of my code – Mohammed Abdeen Apr 16 '21 at 14:18
  • https://stackoverflow.com/questions/30295242/get-the-list-of-child-controls-inside-a-groupbox Use this as a starting point. You don't need all the levels that they have, but the concept is exactly the same. – Logarr Apr 16 '21 at 14:19
  • You want to start from 0 when you count, here you're counting how many times checks were done. – Soleil Apr 16 '21 at 14:21
  • @Soleil yes count is a global var and initiated as zero – Mohammed Abdeen Apr 16 '21 at 14:23
  • 1
    @MohammedAbdeen it is not visible here in your code. You need to add this in your post. Furthermore the initialization should be in the function, or you open the path ot spaghetti code. – Soleil Apr 16 '21 at 14:28

1 Answers1

2

This is a one-liner:

MessageBox.Show(MyGroupBox.Controls.OfType<CheckBox>().Count(b => b.Checked));
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • `MessageBox` is not helping; you rather want a property (int) or an equivalent function. – Soleil Apr 16 '21 at 14:23
  • @Soleil I used MessageBox to mimic the code at the end of the question – Joel Coehoorn Apr 16 '21 at 14:23
  • It makes sense, however inlining everything is not a good practice, you still want a property and use it in the MessageBox. Furthermore, when is it computed ? When any Checked property is changed ? at request ? – Soleil Apr 16 '21 at 14:26
  • @Soleil When `button3_Click` is called, as per the question? –  Apr 16 '21 at 14:29