Hi Ron,
Try something like this...
First of all, when creating the nodes, attach the contextmenustri p to
the nodes ContextMenuStri p. 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.MouseD own event. In that event and
if right mouse button is clicked, clear the contextmenustri p, 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(obje ct sender, EventArgs e)
{
for (int i = 0; i < 5; i++)
{
TreeNode node = new TreeNode(i.ToSt ring());
node.Tag = i;
node.ContextMen uStrip = contextMenuStri p1;
treeView1.Nodes .Add(node);
}
}
private void treeView1_Mouse Down(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Ri ght)
{
contextMenuStri p1.Items.Clear( );
TreeNode node = ((TreeView)send er).GetNodeAt(e .Location);
if (node != null)
{
ToolStripMenuIt em gnu = new ToolStripMenuIt em("Here's the
name: " + node.Tag.ToStri ng());
gnu.Tag = node.Tag;
gnu.Click += new EventHandler(gn u_Click);
contextMenuStri p1.Items.Add(gn u);
}
}
}
void gnu_Click(objec t sender, EventArgs e)
{
MessageBox.Show (((ToolStripMen uItem)sender).T ag.ToString());
}
Ron M. Newman wrote:
Hi,
Just need a little advice. Id like to build *dynamic* context menus for tree
nodes. I'm pretty versed in building context menus and attaching them to
tree nodes.
My question is, what event to I "capture" in order to build the tree node
menu in real time? right click on a tree node? or is it too late?
just FYI: the menu is different for each node and is based on "real time"
parameters. and there's no real way to prepare it in advance.
Thanks
Ron