C#:是否可以在菜单项中获取DropDownItem的索引?

时间:2010-09-27 14:27:24

标签: c# drop-down-menu

是否可以在下拉菜单中获取项目的索引?

2 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分:2)

上面的解决方案在转换为ToolStripMenuItem时可能会抛出一个null,并且会出现一些问题。这个更干净:

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