2

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);
    }
}
2
  • 2
    Thanks a lot, got it fixed. I'm an idiot. Commented Apr 20, 2018 at 14:09
  • 2
    If the answer below helped you fix it, mark it as the chosen answer. If you found your own solution could you post your own answer. Commented Apr 20, 2018 at 14:12

2 Answers 2

2

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");
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I like this better than mine because it finds the menu item using a framework-appropriate feature.
Thank you, @EdPlunkett. You solved the problem though :-) (new instance every time).
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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.