Event handlers for context objects

I am adding right click function on individual treeView nodes in my C # code. Options such as Add, Delete, Rename should appear when the user right-clicks on these tree nodes. Now, depending on the clicked node, I populate the menu using the following statememnts:

contextMenuStrip1.Items.Add ("Add");

Then if I right click on other nodes I use the following:

contextMenuStrip1.Items.Add ("Rename");

There are some nodes where both items should appear: contextMenuStrip1.Items.Add ("Add"); contextMenuStrip1.Items.Add ("Delete");

How can I write separate event handlers for add and remove if both exist in the context of menustrip. I cannot tell if "Add" or "Remove" was clicked. I am currently using the "ItemClicked" event in the ContextMenuStrip to execute my piece of code in the event handler for "Add", but this evemt is also raised when the "Delete" is clicked. Any help would be appreciated.

Thanks, Viren

+2


source to share


2 answers


The ToolStripItem.Add (string text) method returns the ToolStripItem that was added. You have to refer to them this way, when the ItemClicked event is fired, you can determine which one was clicked.

Ex :.



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

      

}

+2


source


You can send a sender object to a ContextMenuItem object and check its name property:

Private Sub ContextItem_Clicker(Byval sender As Object, Byval e As EventArgs)
    Dim castedItem As ContextMenuItem = TryCast(sender, ContextMenuItem)
    If castedItem IsNot Nothing Then
        If castedItem.Name = "whatever" Then
            ' Do something remotely useful here
        End If
    End If
End Sub

      



Or you add different event handlers for different ContextItems.

0


source







All Articles