Reputation: 24116
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?
Upvotes: 1
Views: 2037
Reputation: 14059
You can assign names to the items in theDropDownItems
, that corresponds with their Tag
s. 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;
Upvotes: 1