开发者

removing Items from ToopStripMenuItem dynamically

How do i dynamically remove a ToolStripMenu Item. I have two events that fire one to add a name and one to remove a name. Adding names works. Remo开发者_如何学编程ving does not. When i debug my remove i can see that {Poco} in in the DropDownItems. However when i call remove it does not get removed

// Adding items works as expected
ToolStripMenuItem mi = new ToolStripMenuItem("Poco");
mi.CheckOnClick = true;
myToolStripMenuItem.DropDownItems.Add(mi);

i have tried a lot of things.. what i thought would work was this

// This does not work .. how do i fix this?
myToolStripMenuItem.DropDownItems.RemoveByKey("Poco");

what is the correct way of removing name?


The ToolStripItemCollection.Item property allows you to seek by the item name - as long as it's set for the object itself - so if I assume one cannot add duplicate strings as the menu items, initializing the object with the text to display along with its name should enable you to remove it later:

ToolStripMenuItem mi = new ToolStripMenuItem("Poco"){ Name = "Poco" };

and then further on your processing remove it with the same code you have (I assume it should work):

//Should now work based on MS's comment for the Name property:
//The Name property can be used as a key into the ToolStripItemCollection.
myToolStripMenuItem.DropDownItems.RemoveByKey("Poco");

I unfortunately can't test it at the moment, no .NET on this Mac. :-) However, I'm pretty sure you can Remove() it by directly referencing the object in the collection:

myToolStripMenuItem.DropDownItems.Remove(myToolStripMenuItem.DropDownItems["Poco"]);

Again, too bad I can't test right away for a definite answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜