Home » C# Programming

How do you merge a ContextMenuStrip with a MenuStrip?

I have a MenuStrip with 3 items on it: File, Edit and Help.

I'd like to merge a ContextMenuStrip I've created with the Edit sub menu.  I've been scratching my head and trying without success now for over an hour. 

I've been attempting to use ToolStripManager.Merge() am I on the right track?

Please help!


6 Answers Found


Answer 1

merge menu will create submenu item, for Example

if Main menu contains - File,Edit and Help, and Contextmenu - Open

if you merge context menu to Main menu then - it will like

Main Menu  |  Open.


File              |

Edit             |

Help            |

this format, but if your intension is to insert edit menu to the context menu,

you cant merge to contextmenu, it can be done with the context menuitem, here you can merge the open menuitem to the edit menuitem

context menu is menu, so we can merge it with menu not menuitem.

 if you realy want to assign Main menu's menuitem to the Context menu, you can use this method          




Answer 2

Thanks for your reply.  Sorry but I'm still slightly confused.

I'd like to merge the contents of my ContextMenuStrip, e.g.




into the Edit menu which is contained in the MenuStrip (has menus File, Edit, and Help).

So under the Edit menu I'd like to have Item1, Item2, and Item3.

Could someone please provide a simple code sample for me?  Thanks.

I've tried:

contextMenuStrip.AllowMerge = true;

menuStrip.AllowMerge = true;

ToolStripManager.Merge(contextMenuStrip, menuStrip); // returns false :(


Answer 3

Try this one,

mnuItemEdit.MergeMenu( contextMenuStrip );

now  Edit menu have following sub menu's




 Is that you want.



Answer 4

That won't work.  Here's my code:

MenuStrip menuStrip; // Main menu

ContextMenuStrip contextMenuStrip; // Context menu



ToolStripMenuItem editMenu = (ToolStripMenuItem)menuStrip.Items[1]; // Edit submenu

Can someone please tell me what I need to add.  Thanks!


Answer 5

Okay I worked it out myself.  I feared that I would retire before someone could help me :)

editMenu.DropDown = contextMenuStrip;


Answer 6

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ToolStripManagerTest
  publicpartialclass Form1 : Form
    public Form1()

    privatevoid textBox1_MouseDown(object sender, MouseEventArgs e)
      if (e.Button == MouseButtons.Right)
        ToolStripManager.Merge(this.contextMenuStrip1, this.contextMenuStrip2);

    privatevoid Form1_MouseDown(object sender, MouseEventArgs e)
      if (e.Button == MouseButtons.Right)
        ToolStripManager.RevertMerge(this.contextMenuStrip2, this.contextMenuStrip1);

    ///<summary>/// Required designer variable.///</summary>private System.ComponentModel.IContainer components = null;

    ///<summary>/// Clean up any resources being used.///</summary>///<param name="disposing">true if managed resources should be disposed; otherwise, false.</param>protectedoverridevoid Dispose(bool disposing)
      if (disposing && (components != null))

    #region Windows Form Designer generated code

    ///<summary>/// Required method for Designer support - do not modify/// the contents of this method with the code editor.///</summary>privatevoid InitializeComponent()
      this.components = new System.ComponentModel.Container();
      this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
      this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem();
      this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
      this.textBox1 = new System.Windows.Forms.TextBox();
      this.contextMenuStrip2 = new System.Windows.Forms.ContextMenuStrip(this.components);
      this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem();
      this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem();
      // // contextMenuStrip1// this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
      this.contextMenuStrip1.Name = "contextMenuStrip1";
      this.contextMenuStrip1.Size = new System.Drawing.Size(153, 70);
      // // toolStripMenuItem1// this.toolStripMenuItem1.MergeAction = System.Windows.Forms.MergeAction.Insert;
      this.toolStripMenuItem1.MergeIndex = 0;
      this.toolStripMenuItem1.Name = "toolStripMenuItem1";
      this.toolStripMenuItem1.Size = new System.Drawing.Size(152, 22);
      this.toolStripMenuItem1.Text = "A1";
      // // toolStripMenuItem2// this.toolStripMenuItem2.MergeAction = System.Windows.Forms.MergeAction.Insert;
      this.toolStripMenuItem2.MergeIndex = 1;
      this.toolStripMenuItem2.Name = "toolStripMenuItem2";
      this.toolStripMenuItem2.Size = new System.Drawing.Size(152, 22);
      this.toolStripMenuItem2.Text = "A2";
      // // textBox1// this.textBox1.ContextMenuStrip = this.contextMenuStrip2;
      this.textBox1.Location = new System.Drawing.Point(45, 73);
      this.textBox1.Multiline = true;
      this.textBox1.Name = "textBox1";
      this.textBox1.Size = new System.Drawing.Size(210, 148);
      this.textBox1.TabIndex = 1;
      this.textBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.textBox1_MouseDown);
      // // contextMenuStrip2// this.contextMenuStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
      this.contextMenuStrip2.Name = "contextMenuStrip2";
      this.contextMenuStrip2.Size = new System.Drawing.Size(99, 48);
      // // toolStripMenuItem3// this.toolStripMenuItem3.Name = "toolStripMenuItem3";
      this.toolStripMenuItem3.Size = new System.Drawing.Size(98, 22);
      this.toolStripMenuItem3.Text = "A3";
      // // toolStripMenuItem4// this.toolStripMenuItem4.Name = "toolStripMenuItem4";
      this.toolStripMenuItem4.Size = new System.Drawing.Size(98, 22);
      this.toolStripMenuItem4.Text = "A4";
      // // Form1// this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
      this.ClientSize = new System.Drawing.Size(292, 266);
      this.ContextMenuStrip = this.contextMenuStrip1;
      this.Name = "Form1";
      this.Text = "Form1";
      this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown);


    #endregionprivate System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
    private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem1;
    private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem2;
    private System.Windows.Forms.TextBox textBox1;
    private System.Windows.Forms.ContextMenuStrip contextMenuStrip2;
    private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem3;
    private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem4;



Hi i want to change the intend between the items in Contextmenu strip or Menustrip.

I am migrating an app from VB to .NET.The gap between one menu item to another menu item in VB is very less and in .NET it is more.How to decrease this intend in .NET




I have a MenuStrip with 3 items on it: File, Edit and Help.

I'd like to merge a ContextMenuStrip I've created with the Edit sub menu.  I've been scratching my head and trying without success now for over an hour. 

I've been attempting to use ToolStripManager.Merge() am I on the right track?

Please help!


Hi to all

 i have develop a procedure to load a ContextMenuStrip with some items and sub items dinamically, but im having problems with the itemclick of the control where only items fire the event ItemClick, but not the the subitems of each item (How can items benn firering the event and not the subitems if both was created dinamically)

this is my event

PrivateSub OptionsMenu_ItemClicked(ByVal sender AsObject, ByVal e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles OptionsMenu.ItemClicked

am i missing somnthing on they way to check what subitem was check and what event should be fire?

 this is the code that loaded the ContextMenu

PrivateSub LoadMenuStrip(ByVal StrGroup AsString, ByVal StrGroupAlterno AsString, ByVal StrSequence AsString)
    Dim DT As DataTable, DC As DataTable, TSI As ToolStripMenuItem
    Dim Hijo AsNew ToolStripMenuItem
    Dim Others AsNew ToolStripTextBox



      DT = Conn.GetData("SELECT DISTINCT ACTIVITY, SEQUENCE, [EVENT], (PARAMETER + ' ' + [EVENT]) AS FATHER FROM TBL_MOST_tables WHERE LEFT(activity,1) = '" & IIf(StrGroupAlterno <> "", StrGroupAlterno, StrGroup) & "' and sequence = '" & StrSequence & "'")

      ForEach DR As DataRow In DT.Rows
        TSI = New ToolStripMenuItem()
        TSI.Text = DR("FATHER")
        TSI.ToolTipText = DR("ACTIVITY") & " - " & DR("SEQUENCE")
        DC = Conn.GetData("SELECT (ToolDescription + ' ' + Movements) AS HIJOS, IndexValue FROM TBL_MOST_tables WHERE Activity = '" & DR("ACTIVITY") & "' AND Sequence = '" & DR("SEQUENCE") & "' and EVENT = '" & DR("EVENT") & "'")

        ForEach DR2 As DataRow In DC.Rows
          If DR2("HIJOS").ToString.ToUpper.Trim <> "OTHERS"Then
            Others = New ToolStripTextBox
            Others.Text = "Others"



      OptionsMenu.Show(ueBar, x, y)

    Catch ex As Exception





Hi all,

Just curious why the following code doesn't produce a properly displayed ContextMenuStrip.

I thought ContextMenuStrip.Show() already finishes displaying before the items are cleared.





I have a code that shows a NotifyIcon on the notify area. When i right click over the icon, the ContextMenuStrip appear as normal

The problem is that when i left click over the icon, the menu appear but the TaskBar shows it

Code that i use:

PrivateSub NotifyIcon1_MouseClick(ByVal sender AsObject, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick

If e.Button = Windows.Forms.MouseButtons.Left Then

ContextMenuStrip1.Visible = True



ContextMenuStrip1.Show() make no difference

I read a solution and is invoking the menu or something. Is C/C++/C# code, but i need it on VB.Net


I know that I must be doing something silly, but whenever I try to add a context menu strip to an application, it appears on the form designer and I can add menu items.  As soon as I click off of the form designer, the context menu strip no longer appears on the form, however it does appear as small icon near the bottom of the main form design window.  If I click on that icon, it re-appears on the form.  However, when I run my application, the context menu strip is not there.  I set the Visible property to true and still no luck.  Everything seems to be fine in the auto-generated designer code. Other items (menustrip, buttons, datagrids) seem to work fine.  I'm using VS2010 with .Net 4.0.  Any advice or help would be appreciated.
Quick Steps to reproduce problem:

1. Create a new class, "TestUserControl", that derives from UserControl.  Add a ContextMenuStrip from the VS ToolBox.  Add the following property on the class...

        public ContextMenuStrip OwnContextMenuStrip
            get { return contextMenuStrip1; }
            set { contextMenuStrip1 = value; }

2. Setup a new or existing Windows Application project to reference the new class we created above.  Using the VS Designer, drag a new instance of "TestUserControl" onto the form, and add a couple MenuStripItems through the OwnContextMenuStrip.Items collection.  Then copy/paste the first instance of "TestUserControl1" to create "TestUserControl2." Now here lies the problem: you will find that the MenuStripItems that you added to the original TestUserControl1.OwnContextMenuStrip HAVE BEEN MOVED to TestUserControl2.OwnContextMenuStrip and are NO LONGER PRESENT in the original TestUserControl1.OwnContextMenuStrip.

Any ideas on how this can be resolved? The original MenuStripItems should NOT be disassociated with the original control instance.

PS - I'm using VS2005 - .NET 2.0

Solutions anyone? MUCH THANKS in advance.

I've successfully created a ContextMenuStrip and programatically populated it with the column header text of a datagridview.  Everything is working as expected, but I'd like to implement the following behaviors:

1.  MouseOver the Up/Down scroll arrows on the MenuStrip to cause continuous scrolling just as if you held down a left click on one of the scroll arrows.

2.  No problems getting the MenuStrip to open when I right click a column header, but how can I force the MenuStrip, upon opening, to automatically scroll or focus on the MenuStrip Item that matches the clicked column header(but not select the item)?

3.  Use  of the MouseWheel to scroll through the MenuItems


When creating a right click (ContextMenuStrip) menu for a systray (NotifyIcon) icon, how do I give it the same style as most other context menus?

Most other menus have a nice fade in\out when right clicking on the system tray Icon. In addition they respond immediately when moving between nested levels. I cannot replicate this in Visual Studio 2008 using a simple form, NotifyIcon and ContextMenuStrip assigned. The menu appears harshly with no fade effect regardless of any property.



I have a systemTrayIcon that displays when a service is running. I added a contextmenustrip to it, and have the following sub but the menu does not display or show the msgbox, any idea why?

PrivateSub CORSysTrayIcon_MouseClick(ByVal sender AsObject, ByVal e As System.Windows.Forms.MouseEventArgs) Handles CORSysTrayIcon.MouseClick



 EndSubPrivateSub CORSysTrayIcon_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles CORSysTrayIcon.MouseDoubleClick






How may I trouble shoot this problem? The contextmenu doesnt show up at all. This is a windows service project with a NotifyIcon and ContextMenuStrip.

Imports System.ServiceProcess
Imports System.Threading

PublicClass CORGate

  'This is the thread where the actual work takes placePrivate ServiceThread As Thread
  'This signals the thread to stop processingPrivate StopThread AsBoolean = False'Private images As System.Drawing.Icon() = New System.Drawing.Icon(2) {}Private images0 AsNew System.Drawing.Icon(My.Application.Info.DirectoryPath.ToString & "\icons\systrayOFF.ico")
  Private images1 AsNew System.Drawing.Icon(My.Application.Info.DirectoryPath.ToString & "\icons\systrayON.ico")

  ProtectedOverridesSub OnStart(ByVal args() AsString)
    ' Add code here to start your service. This method should set things' in motion so your service can do its work.
    CORSysTrayIcon.Icon = images1
    CORSysTrayIcon.Text = "Service Started"
    ServiceThread = New Thread(AddressOf DoWork)
  EndSubProtectedOverridesSub OnStop()

    'Try to signla the thread to end nicely and wait up to 20 seconds. 
    StopThread = True
    CORSysTrayIcon.Icon = images0
     'If the thread is still running, abort it.If (ServiceThread.ThreadState And ThreadState.Running) = ThreadState.Running Then
    EndIfEndSubProtectedOverridesSub OnPause()
    CORSysTrayIcon.Text = "Service Paused"
    'If the thread is still running, abort it.
    CORSysTrayIcon.Icon = images0

  EndSubProtectedOverridesSub OnContinue()
    CORSysTrayIcon.Text = "Service Started"
    'If the thread is still running, abort it.
    CORSysTrayIcon.Icon = images1
  EndSubPrivateSub DoWork()
    Dim Counter AsInteger

    CORSysTrayIcon.Text = "Service Processing"DoUntil StopThread
      Counter += 1
      'Debug.WriteLine("not starting iteration #" & Counter.ToString())
    LoopEndSubProtectedOverridesSub Finalize()
  EndSubPrivateSub CORSysTrayIcon_MouseClick(ByVal sender AsObject, ByVal e As System.Windows.Forms.MouseEventArgs) Handles CORSysTrayIcon.MouseClick
  EndSubPrivateSub ToolStripMenuItem1_Click(ByVal sender AsObject, ByVal e As System.EventArgs) Handles ToolStripMenuItem1.Click
    'Start/Pause buttonDim controller AsNew System.ServiceProcess.ServiceController
    controller.MachineName = "."
    controller.ServiceName = "CORGate"Dim status AsString = controller.Status.ToString
    If controller.Status.Equals(ServiceControllerStatus.Paused) Then
    ElseIf controller.Status.Equals(ServiceControllerStatus.Running) Then
    EndIfEndSubPrivateSub ToolStripMenuItem2_Click(ByVal sender AsObject, ByVal e As System.EventArgs) Handles ToolStripMenuItem2.Click
    'Stop buttonDim controller AsNew System.ServiceProcess.ServiceController
    controller.MachineName = "."
    controller.ServiceName = "CORGate"Dim status AsString = controller.Status.ToString
    ' Stop the service



I have a very strange problem. I have a WPF popup window which display a listbox. When I right-click the listbox, I want to show a WinForms ContextMenuStrip as a context menu. For historical reasons I can not easily convert this context menu to a WPF ContextMenu.

The problem is now, that the ContextMenuStrip opens as expected, however I can not select an element with the mouse. It seems, that the control is disabled. When I close the popup-window everything works fine.

Any ideas?

Thanks in advance.





Hi MSDN Forum

I have written a code when the rightmousebutton is clicked in a datgridview there is a menustrip popups. It must contain the word DELETE (dutch verwijderen) and then the name of the company who must be deleted. I have 2 companies in the datagridview. If I clicked for the first time the correct companie is showed in the popupmenu (DELETE Company1), but when I clicked on the second line where Company2 is in the menu popup shows DELETE Company1.
I had set a breakpoint in the routine, but the second time he doesn't come there anymore. The code:



 sender, DataGridViewCellMouseEventArgs e)
   DataGridView DGV = (DataGridView)sender;
 (e.Button == MouseButtons.Right)
 (e.RowIndex > -1 && e.ColumnIndex > -1)
     DataGridViewCell currentCell = DGV.Rows[e.RowIndex].Cells [e.ColumnIndex];

 x = currentCell.ColumnIndex;
 y = currentCell.RowIndex;
 value = DGV.Rows[y].Cells["klantnummer"
 customer = DGV.Rows[y].Cells["Naam"

     DGV.ContextMenuStrip = contextMenuStrip1;
     CTMS.Text = "verwijder "
 + customer;
     ContextMenu contextMenu = new ContextMenu();
     MenuItem m1 = new MenuItem();
     MenuItem m2 = new MenuItem();
     MenuItem m3 = new MenuItem();
     m1.Text = "Verwijder "+ klant;
     m2.Text = "Paste";
     m3.Text = "Exit";
     this.ContextMenu = contextMenu;
     m1.Click +=new EventHandler(m1_Select);
      * */


 sender, EventArgs e)

ANy suggestions?


Full of ideas but don´t know how.

I have DataGridView on a form. When i click on RowHeader of the row, i want to popup a contextMenuStrip control just BottomRight side of the current Mouse position. Below is my code, but its not working.The popup appears just below Upper left corner of the DataGrid instead of the current mouse position.

privatevoid dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
      contextMenuStrip1.Show(dataGridView1, e.Location, ToolStripDropDownDirection.BelowRight);


I want to have a contextmenustrip that dynamically changes itself.

What i have so far is the ability to add items:


And i recieve the data in onHandlerCLick:

void onHandlerClick(object sender, EventArgs e)
CurEd.Text = sender.ToString();

The problem is that i dont seem to be able to get the Index of the button that was clicked (like selectedindex) because sender.ToString() returns the text.

The second problem is that i need multiple dropdowns (so hovering over one will bring up its own drop down), how do i achieve this progamatically?






I have a form that holds dynamically created pictureboxes.  I have a ContextMenuStrip that is opened when the user right-clicks an individual picturebox that allows them to change the Tag of that specific image.  When they click the "Change Tag" item from the ContextMenuStrip, a new form is brought up allowing them to change the Tag in a Textbox.  

My problem is, I can't figure out how to pass the specific picturebox's (that was right-clicked) Tag into the new form so that the user can edit it and set when they click the "set" button.  (Named "Button1" below)

Here's what I have so far: 


Form 1:

 Private Sub ChangeURLToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChangeURLToolStripMenuItem.Click
Dim myItem As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
Dim cms As ContextMenuStrip = DirectCast(myItem.Owner, ContextMenuStrip)

End Sub

And in the ChangeTag Form:

Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    Dim pb As PictureBox = cms.SourceControl
    Dim theURL = pb.Tag.ToString
    theURL = TextBox1.Text

  End Sub


Any help is greatly appreciated.


Hello everybody

I am trying to list all files in a directory into a DataGridView using costum columns.
Actually, in this DataGridView I would like to have multiple ContextMenuStrip, because 3 directories are listed and I need a diferent ContextMenuStrip for each one:


Any idea about how to put diferent contextMenuStrips in the same dataGridView depending on the Row?

Thank you for reading,



I'm writing a library and project that uses the library in the same time. The library contains form that has menuStrip in it. In my project I need to create main window that inherit this form. Is it possible to access the menuStrip (protected) and add via designer new menuItems in main window? Thank you for any help.


My Winform has a menu strip, I'd like it hidden until the user holds down the alt key, then I'd like to show the menu, and move the form contents down a little to provide enough room to show the menu.

This is the same behavior I have in IE 7, and I'd like to implement it my winform.  I don't see an auto-hide property on the menustrip.

Can someone advise.



VS2008  .NET 3.5SP1


I've got a MenuStrip with dropdowns and a Toolstrip with buttons. I don't want the button images in the image margin of the dropdown because they are too small to read properly. I can't seem to find the ShowImageMargin property (in either the MenuStrip or the ToolStripMenuItems) to turn the margin off.

I've constructed the menu items in the designer.

Must be something simple - apologies in advance if it's a dumb question :)



<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure