UniBandit
UniBandit

Reputation: 23

Dynamically adding Context Menu items

For some reason, regardless of how many times the toolstripmenuitem is added to the context menu, it always says the context menu does not contain the item.

ToolStripMenuItem Colour = new ToolStripMenuItem("Colour");

ctmFile.Show(Cursor.Position);
Selecteditem = lvFiles.FocusedItem.Text.ToString();
if (lvFiles.FocusedItem.ImageKey.ToString() == "Folder")
{

    if (ctmFile.Items.Contains(Colour) == false)
    {
        ctmFile.Items.Add(Colour);
    }

}
else
{
    if(ctmFile.Items.Contains(Colour))
    {
        ctmFile.Items.Remove(Colour);
    }
}

Upvotes: 2

Views: 842

Answers (2)

JuanR
JuanR

Reputation: 7783

Just to add on top of Ed's answer, I would recommend using keys instead:

ctmFile.Show(Cursor.Position);
Selecteditem = lvFiles.FocusedItem.Text.ToString();
if (lvFiles.FocusedItem.ImageKey.ToString() == "Folder")
{

    if (!ctmFile.Items.ContainsKey("Colour")) 
    {
        ToolStripMenuItem Colour = new ToolStripMenuItem("Colour");
        Colour.Name= "Colour"; //Add a name (key) to your menu.
        ctmFile.Items.Add(Colour);
    }

}
else
{
    if (ctmFile.Items.ContainsKey("Colour")) 
    {
        ctmFile.Items.RemoveByKey("Colour");
    }
}

Upvotes: 2

You are creating a new menu item and searching for that. But since it was just created, it obviously can't already be in the menu. That's why you never find it there. A different menu item with that text may have been added before, but your code is not looking for that one.

You need to search the menu items for an item that has that text. The code can be simplified a bit in other ways:

var colorItemText = "Colour";
var colorMenuItem = ctmFile.Items.Cast<ToolStripMenuItem>()
                      .FirstOrDefault(mi => mi.Text == colorItemText);

if (lvFiles.FocusedItem.ImageKey.ToString() == "Folder")
{
    //  Create and add if not already present
    if (colorMenuItem == null)
    {
        colorMenuItem = new ToolStripMenuItem(colorItemText);
        ctmFile.Items.Add(colorMenuItem);
    }
}
else if (colorMenuItem != null)
{
    //  Remove if already present. 
    ctmFile.Items.Remove(colorMenuItem);
}

Upvotes: 2

Related Questions