Dynamically creating a second context menu in Winforms

I have a context menu with multiple selections. If the user selects a specific choice, I want the list of options in the second menu to appear. These selections will come from the data store and be unique to that user.

I see how in the designer you can add a set of choices statically representing the user making the choice. However, what do you do when you need to come from data and not create it in a designer?

+2


a source to share


2 answers


One way is to create a cascading menu: in your context menu, add one item as a "parent" item and add one child menu item to the parent item. Then attach an event handler for the parent DropDownOpening

event element and add something like this to it:

private void ParentMenuItem_DropDownOpening(object sender, EventArgs e)
{
    IEnumerable<string> items = GetItems();
    _parentMenuItem.DropDownItems.Clear();
    foreach (var item in items)
    {
        _parentMenuItem.DropDownItems.Add(item);
    }
}

      



This will populate the child menu every time it is opened (add caching if needed).

This will technically work without adding a dummy child, but by adding one, the parent menu will display an arrow indicating that there is a cascading child menu.

+2


a source


I would add the following to set event handlers for new items:



private void ParentMenuItem_DropDownOpening(object sender, EventArgs e)
{
    IEnumerable<string> items = GetItems();
    _parentMenuItem.DropDownItems.Clear();
    int i=0;
    foreach (var item in items)
    {
        _parentMenuItem.DropDownItems.Add(item);
        _parentMenuItem.DropDownItems[i].click += new EventHandler(menuItem_click);
        i++;
    }
}`enter code here`

      

0


a source







All Articles