C # TreeView Collapse / Expand on parent select

It’s hard to explain, so I’ll just tell you what I want to achieve and how I do it, so maybe someone has an idea about what I’m doing wrong.

In my winForm, I have a TreeView control that I populate. All parents have children (any number), but children have no children. Example:

- Parent 1
        Child 1
        Child 2
        Child 3
- Parent 2
       Child 4

The behavior I want is the following:

  • When a user clicks on a child, he is selected (performed by default)
  • When a user clicks on a parent, it must either collapse or expand, but not change any choice.

Point 1 is not a problem, as this is the default behavior of TreeView, but point 2 is another story.

Here is what I have done so far:

, BeforeSelect :

if (e.Node.Parent == null)
    e.Cancel = true;

. , , , . :

if (e.Node.Parent == null)
{
    if (e.Node.IsExpanded)
    {
        e.Node.Collapse();
    }
    else
    {
        e.Node.Expand();
    }
    e.Cancel = true;
}

, , , +, Expand() Collapse() node, e.Cancel = true; .

SelectedNode, Collapse() Expand(), - , , , .

- + , , - .

?

+3
1

try the following:

    private bool allowExpandCollapse = false;

    private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
    {
        e.Cancel = !allowExpandCollapse;
    }

    private void treeView1_BeforeCollapse(object sender, TreeViewCancelEventArgs e)
    {
        e.Cancel = !allowExpandCollapse;
    }

    private void treeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e)
    {
        if (e.Node.Parent == null)
        {
            e.Cancel = true;
        }
    }

    private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
    {
        if (e.Node.Parent == null)
        {
            allowExpandCollapse = true;
            if (e.Node.IsExpanded)
            {
                TreeNode selectedNode = treeView1.SelectedNode;
                e.Node.Collapse();
                allowExpandCollapse = false;
                treeView1.SelectedNode = selectedNode;
            }
            else
            {
                e.Node.Expand();
                allowExpandCollapse = false;
            }
        }
    }
+1
source

All Articles