imdrunkisuppose
imdrunkisuppose

Reputation: 131

Ignore items of a specific type in a foreach loop

I am trying to uncheck a menu's all checkable ToolStripMenuItem items with

foreach (ToolStripMenuItem item in filtersMenu.DropDownItems)
{
   item.Checked = false;
}

ToolStripMenuItem's are all checkable but the problem is compiler gives an InvalidCastException, the loop is trying to operate on ToolStripSeparator items too, how can i fix this, any help would be appreciated, thanks.

Upvotes: 0

Views: 2434

Answers (2)

RononDex
RononDex

Reputation: 4183

Just add an if statement that checks the type of your item:

foreach (ToolStripItem item in filtersMenu.DropDownItems)
{
    // Move to next item if ToolStripSeparator
    if (item is ToolStripSeparator)
        continue;

    item.Checked = false;
}

Upvotes: 7

Abbas
Abbas

Reputation: 14432

You can use the answer of RononDex, which is perfectly good. You can also us this:

foreach(ToolStripMenuItem item in filtersMenu.DropDownItems.OfType<ToolStripMenuItem>())
{
    item.Checked = false;
}

Edit:

If I am not mistaken, RononDex's code should work if modified to this (use ToolStripItem instead of ToolStripMenuItem:

foreach (ToolStripItem item in filtersMenu.DropDownItems)
{
    if (item is ToolStripSeparator)
        continue;

    item.Checked = false;
}

And a bit shorter:

foreach (ToolStripItem item in filtersMenu.DropDownItems)
{
    if (item is ToolStripMenuItem)
        item.Checked = false;
}

This will work because the DropDownItems-property is of the type ToolStripItemCollection. This collection holds items of the type ToolStripItem. Also if you look at the inheritance hierarchy of both the ToolStripMenuItem and the ToolStripSeparator, you'll see they both inherit from ToolStripItem.

More reading:

Upvotes: 6

Related Questions