Hi Ron,
Try something like this...
First of all, when creating the nodes, attach the contextmenustrip to
the nodes ContextMenuStrip. You also need information about what the
treenode represents. Example: Maybe you want to display different
context menu options based on the users rights to the represented
resources. You can store an identifier to each resource in the Tag
property of the corresponding treenode, or even more information.
Consider performance penalties on loading information at treenode
creation time (up front) or at context menu creation time.
Add an eventhandler to the TreeView.MouseDown event. In that event and
if right mouse button is clicked, clear the contextmenustrip, fetch the
clicked node and get the information stored in the Tag propery. Check
for null reference on the node (if the user right clicks, but not on a
node...). Create the menu items, add click event handler, and attach
the Tag value to the menu items (so that you have access to that
information when the user invokes the click event).
See included code snippets below.
This should cover your runtime context menu needs ...
Was this helpful?
Kind regards,
Christer
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++)
{
TreeNode node = new TreeNode(i.ToString());
node.Tag = i;
node.ContextMenuStrip = contextMenuStrip1;
treeView1.Nodes.Add(node);
}
}
private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
contextMenuStrip1.Items.Clear();
TreeNode node = ((TreeView)sender).GetNodeAt(e.Location);
if (node != null)
{
ToolStripMenuItem gnu = new ToolStripMenuItem("Here's the
name: " + node.Tag.ToString());
gnu.Tag = node.Tag;
gnu.Click += new EventHandler(gnu_Click);
contextMenuStrip1.Items.Add(gnu);
}
}
}
void gnu_Click(object sender, EventArgs e)
{
MessageBox.Show(((ToolStripMenuItem)sender).Tag.ToString());
}