C#: Help Iterating through treeview items through NodeMouseClick event – Education Career Blog

I created a piece of code that will display an appropriate groupbox corresponding to the treeview node being clicked like a Preferences menu form. The code does what it’s supposed to do but my problem is figuring out how to make it so that another groubox will not be called into view if another item in the treeview is right clicked.

Detailed

Let’s say there are 3 nodes in the treeview. 0) General; 1) Sounds; and 2) About; If I click node 1Sounds, it will display the appropriate groupbox, but if I right click on treeview node 0General, it will display it’s frame and once I lift up the right click on the mouse, the focus will revert back to 1Sounds but leave the groupbox for node 0) General. How could I failsafe this from happening?

Code

    private void tvFrames_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
    {
        // How would I make sure that it won't display a different groupbox if another treeview node
        // is currently being right clicked (temporarily selected before reverting back to previous focused node item)?
        if (e.Node != null)
        {
            switch (e.Node.Index)
            {
                case 0:
                    ShowGroupBox(groupboxZero);
                    break;

                case 1:
                    ShowGroupBox(groupboxOne);
                    break;

                case 2:
                    ShowGroupBox(groupboxTwo);
                    break;
            }
        }
    }

,

The best answer could be not to use treeView1_NodeMouseClick at all but stick with the standard treeView1_AfterSelect.

You also have a BeforeSelect which could be useful for Saving data or Canceling the move.

,

Can I clarify? You just want this logic to apply on left-click, yes?

    if (e.Button == MouseButtons.Left && e.Node != null)
    {
        switch(...) {
          ...
        }
    }

Also – rather than hard-coding index numbers, you might consider setting the .Tag against the nodes – avoid all the switch etc:

    if (e.Button == MouseButtons.Left && e.Node != null)
    {
        GroupBox grp = e.Node.Tag as GroupBox;
        if(grp != null) ShowGroupBox(grp);
    }

Then all you need to do is set the .Tags in the first place:

    someNode.Tag = groupboxZero;
    someOtherNode.Tag = groupboxOne;
    someThirdNode.Tag = groupboxTwo;

(note – this is just for cnosideration; if your code works, and you are happy – don’t change it).

Leave a Comment