How can I show a context menu only when the user has clicked the root node in a TreeView?
I have a TreeView and a Context Menu. I want to show the Context Menu ONLY when I right click on the ROOT node and not the child nodes.
This is what I have so far. This shows the Context Menu even when I right click on the child nodes. How can I change this so that the Menu shows only when I right click on the root node? Is it possible?
if(e.Button == MouseButtons.Right)
{
// Select the clicked node
treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y)开发者_如何学运维;
if(treeView1.SelectedNode != null)
{
myContextMenuStrip.Show(treeView1, e.Location)
}
}
Yes, it's possible, but you'll need to add some logic to your if
statements that verifies the node the user clicked on is a root node.
But how do we find out if it's a root node? Well, thinking it through, we can define a root node as one that does not have any parents. So you can simply check the Parent
property of the TreeNode
and make sure that it is null
.
Modify your code to look something like this:
if (e.Button == MouseButtons.Right)
{
// Select the clicked node
treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y);
if (treeView1.SelectedNode != null && treeView.SelectedNode.Parent == null)
{
myContextMenuStrip.Show(treeView1, e.Location)
}
}
You want to retain the check that the node itself is not null
, because you don't want to show the context menu when they haven't clicked on a node, but you need to add the check for a parent, because that tells you whether or not it's a root node. The way you indicate that programmatically is using a logical AND, which is the &&
operator in C#.
Check that the node you clicked on is the root node instead of checking for it being null
.
You can also use the Level
property:
http://msdn.microsoft.com/EN-US/library/386b25wy(v=VS.110,d=hv.2).aspx
If e.Button = MouseButtons.Right Then
' Select the clicked node
treeView1.SelectedNode = treeView1.GetNodeAt(e.X, e.Y)
If treeView1.SelectedNode.Level = 0 Then
myContextMenuStrip.Show(treeView1, e.Location)
End If
End If
精彩评论