Build dynamic context menus for trees


R

Ron M. Newman

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
 
Ad

Advertisements

C

christer.dk

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());
}
 
Ad

Advertisements

W

waheed iqbal

You must write the code on mouse down event.

Identify the Tree Node by custom code and then perform you task.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top