Get index of ToolStripMenuItem.DropDownItems for specific Tag without foreach loop

StackOverflow https://stackoverflow.com/questions/22502333

  •  17-06-2023
  •  | 
  •  

Вопрос

Is there a way to get index of ToolStripMenuItem.DropDownItems for an item in the collection having a specific tag, without using foreach loop?

I am currently doing it like this:

private void button1_Click(object sender, EventArgs e)
{
    Form2 myForm2 = new Form2();
    myForm2.OnTemplateUpdated += new Form2.TemplateUpdatedHandler(myForm2_OnTemplateUpdated);
    myForm2.Show();
}

void myForm2_OnTemplateUpdated(Form s, TemplateUpdatedEvent e)
{
    int index = 0;
    foreach (ToolStripMenuItem myMenuItem in templatesToolStripMenuItem.DropDownItems)
    {
        if ((string)myMenuItem.Tag == e.TemplateId)
        {
            templatesToolStripMenuItem.DropDownItems[index].Text = e.NewName;
            break;
        }
        index++;
    }
}

I know templatesToolStripMenuItem.DropDownItems has a IndexOf() method, but I am not having any luck trying to use it like this:

int menuItemIndex = templatesToolStripMenuItem.DropDownItems
    .IndexOf(new ToolStripMenuItem() { Tag = e.TemplateId });

The menuItemIndex is always -1... perhaps I'm using the method incorrectly?

Это было полезно?

Решение

You can assign names to the items in theDropDownItems, that corresponds with their Tags. For instance:

templatesToolStripMenuItem.DropDownItems.Add(new ToolStripMenuItem("Item text") { Tag = 1, Name = "item1" });

Thus you can get the desired item as follows:

templatesToolStripMenuItem.DropDownItems["item" + e.TemplateId].Text = e.NewName;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top