Search code examples
vb.netcontextmenustrip

Adding menustripitems on top of existing ones


In my simple WinForm application I have a ContextMenuStrip. This is palced during design time and few items have been added in designer mode. For example following items are added during design time,

--------
Option 1
Option 2
Option 3
--------
Close
Exit

Now I am getting the Groups from database. Each Group can have multiple users. So first I create the Groups using this code,

For Each drGroup In dtGroups.Rows
   Dim groupMenu As New ToolStripMenuItem() With {.Text = drGroup ("GroupName"),
                                                       .Name = RemoveWhitespace(drGroup ("GroupName"))
                                                      }
   myCMS.Items.Add(groupMenu)                
Next

I am not mentioning the code for adding sub items for groups as it is beyond the context of this question. Now my context menu strip is like this,

--------
Option 1
Option 2
Option 3
--------
Close
Exit
Group 1
Group 2
Group 3
Group 4
Group 5

But I want the output like this,

Group 1
Group 2
Group 3
Group 4
Group 5
--------
Option 1
Option 2
Option 3
--------
Close
Exit

I have no idea how I can achieve this. One way could be to remove the existing items and re-add them after all dynamic items are created but is there any other solution.


Solution

  • Instead of adding items, you can simply insert them into the beginning of the list:

    myCMS.Items.Insert(0, groupMenu)
    

    This will change the "index" values of the existing items in the current list.