Search code examples
c#winformstreeviewcontextmenustrip

Setting the ContextMenuStrip for all nodes on a level in a TreeView?


I'm really struggling with coming up with a clever way to set the correct ContextMenuStrip for the the right node. I have a Tree View with 3 levels. And alongside with it I have 3 different ContextMenuStrips that I've created, each for their respected levels. Is there a simple way or trick that anyone's come across for solving this problem?

Also is there a way to have it so right clicking a node makes it the selected node? Or aka does the same thing as a left click.

Sorry for the 2 in 1 but I imagine if someone knows enough on this topic to solve one of my problems there's a good chance they'll know the second as well.

EDIT: I found a solution to my second problem with this line of code:

treeView.NodeMouseClick += (sender, args) => treeView.SelectedNode = args.Node;

Solution

  • Use the NodeMouseClick event to set the ContextMenuStrip property of the selected node:

    void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) {
      if (e.Button == MouseButtons.Right) {
        treeView1.SelectedNode = e.Node;
      }
    
      if (e.Node.Level == 0) {
        e.Node.ContextMenuStrip = cms1;
      } else if (e.Node.Level == 1) {
        e.Node.ContextMenuStrip = cms2;
      } else  if (e.Node.Level == 2) {
        e.Node.ContextMenuStrip = cms3;
      }
    }