Click here to Skip to main content
15,922,419 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
Such a problem!!!
my program adds Items to a MenuStrip during the RunTime
I need to give a function to each of those new Items but ... how to write a code that calls this function if the Item was not created yet???
in other words,
the program adds an Item (car name) to the MenuStrip each time I press a button ... I want to give the user some information about the Car he chose from the MenuStrip!!!

how can I do that?
Posted
Comments
Sergey Alexandrovich Kryukov 28-Sep-11 17:59pm    
Tag it! WPF, Forms, what?
--SA

Apparently, you cannot add anything to something which does not exist. Equally apparent thing is that you never need it. Something which does not exist cannot help.

Your problem is very simple. You need to add an event handler to an invocation list of an event of the existing menu item, the one you just created. Just do it:

C#
class ToolStripItemData { //it's often helpful to define some data type, to put in each item
//... your car data, for example
}

//...

System.Windows.Forms.ToolStripItem.Click item =
    new System.Windows.Forms.ToolStripDropDownItem(); //for example
item.Tag = new ToolStripItemData(/* ... */); // some data specific to a particular item instance (e.g. car data)

//...

item.Click += (sender, eventArgs) => {
    System.Windows.Forms.ToolStripItem item =
        (System.Windows.Forms.ToolStripItem)sender;
    ToolStripItemData carData = (ToolStripItemData)item.Tag; //make sure you read what you put there
    //some action depending on carData
} //item.Click


In case you use C# v.2, you need to use older (longer) syntax for anonymous delegate instance, with explicit type declaration:

C#
item.Click += delegate(object sender, System.EventArgs eventArgs) {
//...
}


See System.Windows.Forms.ToolStripItem.Click: http://msdn.microsoft.com/en-us/library/system.windows.forms.toolstripitem.click.aspx[^].

—SA
 
Share this answer
 
v4
C#
// You can in ItemAdded event of your menuStrip call your function
private void menuStrip1_ItemAdded(object sender, ToolStripItemEventArgs e)
{
    // Calling your function
}


Perhaps you mean is this:

C#
private void menuStrip1_ItemAdded(object sender, ToolStripItemEventArgs e)
{
    // You can create event handler for each added item during the RunTime
    e.Item.Click += new EventHandler(Item_Click);
}

void Item_Click(object sender, EventArgs e)
{
    // TODO: code
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900