Search code examples
c#winformsdrop-down-menumenustrip

How to add a scrollbar to a Menu item dropdown?


There are too many items in the menu strip item.
Like this:

Long menu dropdown

It looks very long and bad. I want to add a scroll bar to menu strip items.
I want to see 3 of these items with the help of the scroll bar.
How can I do it?


Solution

  • You can set the maximum height of a MenuItem's DropDown using the ToolStripMenuItem.DropDown MaximumSize property.

    You can determine the height of the DropDown based on the maximum number of Items you want to show. Or any other measure that makes sense in your scenario (maybe a measure that fits the current ClientSize.Height of a Form).

    To specify a height relative to a maximum number of sub items (here, maxSubMenuItems), sum the Height of the first maxSubMenuItems sub items and use this measure to set the MaximumSize property.

    The standard (top and bottom) scroll buttons will appear.

    Here, I'm using a maxHeight + (maxHeight / maxSubMenuItems) value, to add some space, at the top and bottom of the dropdown, otherwise a menu may not fit in and it also looks better :)

    Insert this code in the Form's Constructor (after InitializeComponent()) or in Form.Load:

    int maxSubMenuItems = 6;
    
    if (toolStripMenuItem1.DropDownItems.Count > maxSubMenuItems) {
        int maxHeight = toolStripMenuItem1.DropDownItems
            .OfType<ToolStripMenuItem>()
            .Take(maxSubMenuItems)
            .Sum(itm => itm.Height);
    
        toolStripMenuItem1.DropDown.MaximumSize = 
           new Size(toolStripMenuItem1.DropDown.Width, maxHeight + (maxHeight / maxSubMenuItems));
    }
    

    ► This can come in handy when you have to show a list of sub-items that represent Fonts, for example. So you may want to show a string drawn using the Font name in the list. Or similar situations, when you have to present a single, potentially long, dropdown.

    In other cases, try to limit the number of items per ToolStripMenuItem using sub menus.