.NET Framework: adding a separator to a context menu


To add a separator menu item to a context menu in a .NET Framework application, you simply have to add a menu item with the Text property set to "-".


Here is an example of the required code:


// creating the context menu
System.Windows.Forms.ContextMenu contextMenu = new System.Windows.Forms.ContextMenu();


// creating a first menu item
System.Windows.Forms.MenuItem menuItem1 = new System.Windows.Forms.MenuItem();
menuItem1.Click += new EventHandler(MenuItem1_Click);
menuItem1.Index = 0;
menuItem1.Text = "Menu Item 1";


// creating the separator menu item
System.Windows.Forms.MenuItem menuItem2 = new System.Windows.Forms.MenuItem();
menuItem2.Index = 1;
menuItem2.Text = "-";


// creating a second menu item
System.Windows.Forms.MenuItem menuItem3 = new System.Windows.Forms.MenuItem();
menuItem3.Click += new EventHandler(MenuItem2_Click);
menuItem3.Index = 2;
menuItem3.Text = "Menu Item 2";


// adding the menu items to the context menu
contextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { menuItem1, menuItem2, menuItem3 });


// assigning the context menu to my UI control
myControl.ContextMenu = contextMenu;


Skip to main content