1

I have a toolstrip. For this toolstrip, I am adding ToolStripSplitButton and for this ToolStripSplitButton, I am adding toolstrip items, including ToolStripSeparator. In the click event of the toolstrip items I am retrieving items from the ToolStripSplitButton dropdown using below code.

 ToolStripDropDown tditems = ((System.Windows.Forms.ToolStripDropDownItem)(items[0])).DropDown;
foreach (ToolStripMenuItem item in tditems.Items)
{
//something here
}

As the dropdown items have both toolstrip items and ToolStripSeparator at runtime, it is giving following error.

Additional information: Unable to cast object of type 'System.Windows.Forms.ToolStripSeparator' to type 'System.Windows.Forms.ToolStripMenuItem'.

Can anybody help me?

Thanks

H H
  • 263,252
  • 30
  • 330
  • 514

1 Answers1

7

If you are using .NET 3.5, you could use the OfType extension method as follows.

foreach (var item in tditems.Items.OfType<ToolStripMenuItem>())
{
    // something here
}
Jeff Yates
  • 61,417
  • 20
  • 137
  • 189