Dolu bolu
Dolu bolu

Reputation: 189

How to get dynamically created ToolStripMenuItem by name in a Windows application?

Form2:

private ToolStripMenuItem mHelp;
private ToolStripMenuItem apProposToolStripMenuItem;
public void intializecomponent()
{
this.mHelp = new ToolStripMenuItem();
      this.contentsToolStripMenuItem = new ToolStripMenuItem();
      this.apProposToolStripMenuItem = new ToolStripMenuItem();
     this.mHelp.DropDownItems.AddRange(new ToolStripItem[2]
          {
            (ToolStripItem) this.contentsToolStripMenuItem,
            (ToolStripItem) this.apProposToolStripMenuItem
          });
          this.mHelp.Name = "mHelp";
          this.mHelp.Size = new Size(44, 20);
          this.mHelp.Text = "Help";
          this.contentsToolStripMenuItem.Name = "contentsToolStripMenuItem";
          this.contentsToolStripMenuItem.Size = new Size(122, 22);
          this.contentsToolStripMenuItem.Text = "Contents";
          this.contentsToolStripMenuItem.Click += new EventHandler(this.contentsToolStripMenuItem_Click);
          this.apProposToolStripMenuItem.Image = (Image) componentResourceManager.GetObject("apProposToolStripMenuItem.Image");
          this.apProposToolStripMenuItem.Name = "apProposToolStripMenuItem";
          this.apProposToolStripMenuItem.Size = new Size(122, 22);
          this.apProposToolStripMenuItem.Text = "About";
          this.apProposToolStripMenuItem.Click += new EventHandler(this.apProposToolStripMenuItem_Click);
    this.Load += new EventHandler(this.DocumentSpace_Load);
}

How to find apProposToolStripMenuItem on the form? I tried to remove a particular ToolStripMenuItem, but it doesn't work and I can't find apProposToolStripMenuItem.

Form1:

ToolStripMenuItem mi = new ToolStripMenuItem("apProposToolStripMenuItem") { Name = "About" };
mi.DropDownItems.RemoveByKey("About");

Upvotes: 1

Views: 454

Answers (2)

Reza Aghaei
Reza Aghaei

Reputation: 125292

Assuming you have access to the MenuStrip or the ToolStrip on the form, then you can use Descendants extension method to find all items, regardless of its location in hierarchy of menus and its parent item. for example:

var item = menuStrip1.Descendants()
    .Where(x => x.Name == "printToolStripMenuItem").FirstOrDefault();
item?.GetCurrentParent().Items.Remove(item);

Upvotes: 1

Racil Hilan
Racil Hilan

Reputation: 25361

You can remove it by name like this:

mHelp.DropDownItems.RemoveByKey("apProposToolStripMenuItem");

You can also remove it directly like this:

var about = mHelp.DropDownItems["apProposToolStripMenuItem"]
mHelp.DropDownItems.Remove(about);

Upvotes: 2

Related Questions