Search code examples
c#winformstoolstrip

Hide ImageMargin and CheckMargin in ToolStripDropDownMenu


I'm trying to set the ImageMargin and CheckMargin properties in every ToolSTripDropDownMenu within a certain ToolStrip.

foreach (ToolStripDropDownButton tsd in toolStrip1.Items)
{
    ((ToolStripDropDownMenu)tsd.DropDown).ShowImageMargin = false;
    ((ToolStripDropDownMenu)tsd.DropDown).ShowCheckMargin = false;
}

An exception is thrown saying the following:

System.InvalidCastException: Unable to cast object of type 'System.Windows.Forms.ToolStripButton' to type 'System.Windows.Forms.ToolStripDropDownButton'.

The ToolStrip contains controls besides ToolStripDropDownButtons (namely ToolStripButtons and ToolStripLabels) so I can see where the error is occuring. What I can't wrap my head around is how to modify ONLY the ToolStripDropDownButtons. ToolStripDropDownMenu doesn't contain a CheckMargin or ImageMargin property by default unlike a standard ContextMenu.


Solution

  • The foreach statement doesn't perform any filtering, so when you declare the item type to be ToolStripDropDownButton as you have, it will attempt to cast every item in the sequence to that type. Since that's not possible for some of the items, you need to declare a less specific type and check for the instances you want:

    foreach (ToolStripItem tsi in toolStrip1.Items)
    {
        if (tsi is ToolStripDropDownButton) {
            ToolStripDropDownButton tsd = (ToolStripDropDownButton)tsi;
            ((ToolStripDropDownMenu)tsd.DropDown).ShowImageMargin = false;
            ((ToolStripDropDownMenu)tsd.DropDown).ShowCheckMargin = false;
        }
    }