views:

1044

answers:

2

Hi,

I am adding a right click functionality on individual nodes of a treeView in my C# code. The options like "Add", "Delete", "Rename" should pop up when the user right clicks in those nodes on the tree. Now depending on the node that is being clicked, I am filling up the menu as using the following statememnts:

contextMenuStrip1.Items.Add("Add");

Then if a different nodes is right clicked I use the following:

contextMenuStrip1.Items.Add("Rename");

There are some nodes where both the items have to be shown: contextMenuStrip1.Items.Add("Add"); contextMenuStrip1.Items.Add("Delete");

How do I write seperate event handlers for Add and Delete when both of them exist in the context menustrip. I am not able to differentiate whether "Add" or "Delete" was clicked. Currently I am using the "ItemClicked" event on the ContextMenuStrip to execute my piece of code in the event handler for "Add" but this evemt also gets raised when "Delete" is clicked. Any help would be appreciated.

Thanks, Viren

A: 

Yould cast the sender Object to a ContextMenuItem and check it's name property

Private Sub ContextItem_Clicker(Byval sender As Object, Byval e As EventArgs)
    Dim temp As ContextMenuItem = TryCast(sender, ContextMenuItem)
    If temp IsNot Nothing Then
        If temp.Name = "whatever" Then
        End If
    End If
End Sub

Bobby

Edit: Or you add different Event-Handlers for it.

Bobby
+1  A: 

The ToolStripItem.Add(string text) method returns the ToolStripItem that was added. You should reference them that way, when the ItemClicked event gets fired you can determine which one was clicked.

E.x.:

using System;
            using System.Windows.Forms;
            namespace WindowsFormsApplication6
            {
static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        using (Form form = new Form())
        {
            form.ContextMenuStrip = new ContextMenuStrip();
            ToolStripItem addMenuItem = form.ContextMenuStrip.Items.Add("Add");
            ToolStripItem deleteMenuItem = form.ContextMenuStrip.Items.Add("Delete");

            form.ContextMenuStrip.ItemClicked += (sender, e) =>
          {
              if (e.ClickedItem == addMenuItem)
              {
                  MessageBox.Show("Add Menu Item Clicked.");
              }
              if (e.ClickedItem == deleteMenuItem)
              {
                  MessageBox.Show("Delete Menu Item Clicked.");
              }
          };
            Application.Run(form);
        }
    }
}

}

hjb417