views:

282

answers:

2

I've got a sequence of checkboxes on a C# Winform. Each checkbox can have some options on it, which is really just another set of checkboxes that are just indented into the page a bit.

What I'm trying to achieve is when you tick one of the parent checkboxes then all it's child checkboxes get ticked. And the opposite when a parent checkbox is unticked where all it's child checkboxes get unticked.

Then I need to have it so that if a child checkbox get's ticked then it ticks it's parent, or at least ensures that the parent is ticked. Ie you can't have a child without the parent. And if a child is unticked then if all the other children are unticked then the parent needs to be unticked.

I'm doing this with event handlers on the checkboxes but I've come against the problem where checking a child with the cursor then programmatically checks the parent which then programmatically checks all it's children.

I would very much appriciate any advice on how to program this in such a way that it doesn't have a problem like this.

+2  A: 

Something like this should work.

    private void checkBox1_CheckedChanged(object sender, EventArgs e)
    {
        if (checkBox1.Focused)
        {
            checkBox2.Checked = checkBox1.Checked;
            checkBox3.Checked = checkBox1.Checked;
            checkBox4.Checked = checkBox1.Checked;
        }
    }

    private void subCheckBox_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox theCheckbox = sender as CheckBox;
        if (theCheckbox.Focused)
        {
            checkBox1.Checked = checkBox2.Checked || checkBox3.Checked || checkBox4.Checked;
        }
    }

Checkboxes 2, 3, and 4 are all tied to the same handler for my example.

Hope that helps!


Obviously, this makes some assumptions as it is just an example. I'm relying on user input (Focused property) to control the flow. There are other solutions, I'm sure.

itsmatt
Ah I see so you only do stuff if the checkbox is focused, thereby avoiding the check chains I've got a problem with. Brilliant. Thanks
Dan Revell
+1  A: 

You could also use a treeview control with TreeView.CheckBoxes = true. This way you'd already have the hierarchical structure by default.

OG
I did consider using this but I need to do some weird things I've not mentioned here that the TreeView won't support. Thanks for the suggestion all the same
Dan Revell