2

Is it possible to get the index of an item in a dropdown menu?

4
  • Please elaborate, there is not enough information. Commented Sep 27, 2010 at 14:29
  • I'm not sure if I understand what you're trying to do. Could you provide more details about your specific scenario? Commented Sep 27, 2010 at 14:30
  • What kind of dropdown menu? WPF/Forms, etc.?
    – jsmith
    Commented Sep 27, 2010 at 14:30
  • I have a menu item called "Projects" and everytime i create a new project or open a project it is added to this menuitem as a Dropdown item. When i then click the dropdown item i want to pass along the index of the menu item.
    – Bildsoe
    Commented Sep 28, 2010 at 7:33

2 Answers 2

7
private void item_Click(object sender, EventArgs e)
{
    ToolStripMenuItem item = sender as ToolStripMenuItem;
    if (item != null)
    {
        int index = (item.OwnerItem as ToolStripMenuItem).DropDownItems.IndexOf(item);
    }
}
2
  • @Petar - one of the menu items has items add'ed to the DropDownItems list. And i want to find the index of the dropdown item i click on.
    – Bildsoe
    Commented Sep 28, 2010 at 7:35
  • @devnull - works perfectly! Thanks a bunch! I've accepted the answer.
    – Bildsoe
    Commented Sep 28, 2010 at 8:01
2

The above solution may throw a null when casting to ToolStripMenuItem and there's some fluff. This one is cleaner:

private void item_Click(object sender, EventArgs e)
{
    ToolStripMenuItem item = sender as ToolStripMenuItem;
    if (item != null)
    {
        int index = ContextMenuStrip.Items.IndexOf(commentMenuItem);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.