Disable or Enable Context Menu Items For a TreeView



In this article I would like to show how to disable and enable context menu items for a TreeView. In some cases we need this for example we have to hide unnecessary items when clicking a specific node of a tree view.

For this use the following controls:

  1. TreeView
  2. Context Menu

Add the required Nodes for tree view and required items for context menu.

Sample Image after adding some sample data to the Form:

DisEnab1.gif

The important point to remember when adding nodes to a tree view is to have a necessary TAG for individual nodes. To add a TAG for the nodes follow as described below.

Right-click on the tree view to add or edit nodes; you will have the following. If you already have nodes added then you will have the option as Edit Nodes, if not then it will be Add Nodes. Select whichever one it is.

DisEnab2.gif

After selecting Edit nodes you will have a Tree Node editor as follows; select the desired Node to add a TAG.

DisEnab3.gif

Here I am assigning a TAG value to the Root Node as shown in the figure:

DisEnab4.gif

Like that add the required TAGS as you need.

For the context menu I added the two items ROOT and CHILD. You can add more as needed.

Code to Enable or Disable context menu items:

private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
treeView1.SelectedNode = e.Node;
if (Convert.ToInt16(e.Node.Tag) == 1)
{
childToolStripMenuItem.Enabled = false;
rootToolStripMenuItem.Enabled = true;
}
if (Convert.ToInt16(e.Node.Tag) == 2)
{
childToolStripMenuItem.Enabled = true;
rootToolStripMenuItem.Enabled = false;
}
}

Code for showing context menu on TreeView:

private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
contextMenuStrip1.Show(treeView1, e.Location);
}
location = e.Location;
}

Sample output when user clicks on Root Node:

DisEnab5.gif

Sample output when user clicks on Child Node:

DisEnab6.gif

That's how we can enable or disable the necessary context items. If you have any questions then let me know. Go through the attached code for further reference.

Happy Coding.

Up Next
    Ebook Download
    View all
    Learn
    View all