当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - hierarchical winform checkboxes

问题描述:

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.

网友答案:

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.

网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: