TreeView context menus

Recently I wanted to add a right click context menu to a list of items in a TreeView control in C# and winforms.

It was relatively simple but there is one small thing that isn’t as obvious. That is that it is good to allow users to be able to right click an item and open it, delete it, run it or whatever you action is on the your context menu, without having to left click select it first. Less clicks == good.

So first create your TreeView, you can do this by dragging the control onto your form or custom control.

Now add a ContextMenuStrip item from the toolbox in the same way.

Go to the properties of the TreeView and set the ContextMenuStrip property to be the one which you just created.

Now add items to your context menu by click the small arrow drop down at the top right corner of it, see the image below:

contextMenuAddItems

You will then be able to click Edit Items:

contextMenuAddItems2

From you can add menu items, so add the ones you want and name them appropriately and change the menu text for them as well.

Now for the right clicking to actually work without a user selecting the item first we need to add this line of code somewhere sensible, i’ve put mine just after the InitializeComponent(); line in the form.

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

This line of code means that the node you right click on will be selected as you right click, this is very important as in most cases you will want the actions in the context menu to be applicable to the item you have right clicked.

So now if you click your ContextMenuStrip control that you added your items to you should see your menu at the top of the form (while in design mode the context menu is just at the top of the form). Double click one of your items to add some functionaility.

One of my right click menu items is called openFile the click handler is below, this is where it is important to be able to have your SelectedNode set to the one you right clicked on.

// Code executed when a context menu item is clicked
private void openFile_Click(object sender, EventArgs e) {
    
    // Here we can now reference yourTreeView.SelectedNode
    DoSomething(yourTreeView.SelectedNode.Text);
}

 

If we did not have that first line of code ( the NodeMouseClick event handler ) the above code would throw an exception as the SelectedNode would be null (unless the user did a left click first).

Happy right clicking!

Leave a Reply

Your e-mail address will not be published. Required fields are marked *