Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

ToolStripMenuItems.DropDownItems - Indexer not working

Status
Not open for further replies.

MadJock

Programmer
May 25, 2001
318
GB
Hi All,

I'm sure the answer to this is going to be obvious but I've googled it to no avail!!

I want to dynamically build a menu. When doing so, I want to check if an item already exists but struugling!

Simplified Example:
Code:
// this adds an item called 'item1' to the 'Tools' menu
toolsToolStripMenuItem.DropDownItems.Add(new ToolStripMenuItem("Item1"));

            if (toolsToolStripMenuItem.DropDownItems.ContainsKey("Item1"))
            {
                MessageBox.Show("WORKED");
            }
            else
            {
                MessageBox.Show("NOT WORKED");
            }

Obiously, when I am adding to DropDownItems, I have specified no key, but I cannot see any way to do so!

Any help appreciated,

Graeme



"Just beacuse you're paranoid, don't mean they're not after you
 
You could use the ItemAdded event handler to capture when an item is added and then perform your check.

Code:
private void Form1_Load(object sender, EventArgs e)
{
    menuStrip1.ItemAdded += new ToolStripItemEventHandler(menuStrip1_ItemAdded);
    menuStrip1.Items.Add("Test");
    menuStrip1.Items.Add("Test");
}

void menuStrip1_ItemAdded(object sender, ToolStripItemEventArgs e)
{
    if (menuStrip1.Items.Contains(e.Item))
    {
        MessageBox.Show("The item already exists!");
    }
}
 
Hi PG001,

Thanks for reply. Unfortunately I over-simplified my issues - I have other reasons for wishing to refer to the item by index after it's been added.

Do you know of any way to specify the index when I add the item? If not, I guess I could create a seperate map of name to numbered index.

Thanks,

Graeme

"Just beacuse you're paranoid, don't mean they're not after you
 
I think the problem in your original code is that your item doesn't have a name.
Code:
new ToolStripMenuItem("Item1")
Here, "Item1" is the Text property not the Name property.

For example, this works:
Code:
ToolStripMenuItem file = new ToolStripMenuItem("File");
file.Name = "FileMenuItem";
myMenu.Items.Add(file);

if (myMenu.Items["FileMenuItem"] != null)
{
    MessageBox.Show("'File' Exists!");
}
else
{
    MessageBox.Show("'File' Does Not Exist!");
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top