Lignumsus
Lignumsus

Reputation: 1

C# Execute Method for selected CheckBoxes. Different Method for each CheckBox

So I have a bunch of CheckBoxes on a Form with a Button at the bottom that I want to click and it Executes the Methods for those Checked CheckBoxes.

Each CheckBox will use its own Method.

Seems Like a Common/Simple thing to do. Yet I have found nothing too helpful searching around regarding dealing with multiple CheckBoxes on one Event.

I am relatively new to programming and I'm learning on my own.

Idk if there's a simple for or foreach loop I can use in conjunction with something else to make this simpler, but I don't even know a long way to make it work...

All I can Come up with is a bunch of if statements under button click event to test if checked and if so run method. However, this seems like the wrong way to do this.

    private void btnExecutedSelected_Click(object sender, EventArgs e)
    {
        if (ChkBox_Test.Checked == true)
        {
            ClassName.MethodName();
        }
        //Then an if statement for each CheckBox

    }

Any Help Much Appreciated

Upvotes: 0

Views: 1211

Answers (2)

Sabri
Sabri

Reputation: 199

You can do something like this:

private void CheckBoxOperations(Control parentControl)
            {
                foreach (Control c in parentControl.Controls)
                {
                    if (c is CheckBox)
                    {
                        if (((CheckBox)c).Checked)
                        {
                            //DoSomething
                        }
                    }
                    if (c.HasChildren)
                    {
                        CheckBoxOperations(c);
                    }
                }
            }


     private void btnExecutedSelected_Click(object sender, EventArgs e)
        {
           CheckBoxOperations(this);
        }

Upvotes: 0

jhilgeman
jhilgeman

Reputation: 1583

There are several ways to approach this, and usually the best ways are a little more advanced, but this is a good opportunity to learn some basics about delegates, which are like a mix between variables and methods/functions. For now, think of them like a card in Monopoly that tells you to go directly to jail. The card itself isn't really anything except an instruction that you pick up. When you USE / read the card, you have to follow the resulting instruction, which is to go to jail. So delegates are sort of like those cards.

To get an idea of how they work, create a new Winforms app, drop 4 checkboxes on the form and a button. Don't worry about renaming them. Then add in the following code:

    // This defines the "monopoly cards"
    // Community Chest cards give or take money, so we'll expect an int to be returned 
    public delegate int CommunityChestCard();

    // Chance cards just do things without any return values
    public delegate void ChanceCard();

    private void Form1_Load(object sender, EventArgs e)
    {
        checkBox1.Tag = new ChanceCard(GoDirectlyToJail);
        checkBox2.Tag = new ChanceCard(AdvanceToGo);
        checkBox3.Tag = new CommunityChestCard(WinBeautyContest);
        checkBox4.Tag = new CommunityChestCard(PayDoctorsFees);
    }

    private void GoDirectlyToJail()
    {
        MessageBox.Show("You went to jail!");
    }

    private void AdvanceToGo()
    {
        MessageBox.Show("You advanced to Go!");
    }

    private int WinBeautyContest()
    {
        MessageBox.Show("You won $20 in a beauty contest!");
        return 20;
    }

    private int PayDoctorsFees()
    {
        MessageBox.Show("You had to pay $50 in doctor's fees!");
        return -50;
    }

    // Now when we click the button, we'll loop through our checkboxes, 
    // see which ones were checked, and then execute the methods defined
    // in the associated chance/communitychest cards.
    private void button1_Click(object sender, EventArgs e)
    {
        // this.Controls is a collection of the child controls on the current form
        foreach(Control ctl in this.Controls)
        {
            // See if the control is a CheckBox
            if(ctl is CheckBox)
            {
                // It is - let's cast it for easier coding...
                CheckBox chk = (CheckBox)ctl;

                // Is it checked?
                if (chk.Checked)
                {
                    // Yep! Does it have a value in its Tag?
                    if (chk.Tag != null)
                    {
                        if(chk.Tag is CommunityChestCard)
                        {
                            CommunityChestCard ccCard = (CommunityChestCard)chk.Tag;

                            // Call the function on the card and get the result
                            int adjustMoneyByAmount = ccCard();
                        }
                        else if(chk.Tag is ChanceCard)
                        {
                            ChanceCard cCard = (ChanceCard)chk.Tag;

                            // Call the function on the card
                            cCard();
                        }
                    }
                }
            }
        }
    }

Now, just some words of warning - I used the Tag property as a quick fix to cut down on extra coding for illustration purposes. As you get better with code and custom/extended controls, you might want to have your own properly-typed properties for these kinds of things. Using Tag is NOT an elegant solution.

If you run that code as described, you should be able to check some of the checkboxes and click the button and see the resulting functions being executed.

I'd also suggest not just looping through all the controls on a form and checking to see if they're checkboxes. You seemed to have some trouble with looping through controls, so that approach was there as an example. Checkboxes can be grouped together in many different ways. You might consider a List object and adding your checkboxes to that list. That way, you can simply loop through that List later and you'll know exactly which controls you're dealing with (no ugly casting or checking to see if a control is a checkbox).

Upvotes: 1

Related Questions