How to handle menu items in C# for passing values
I am working in Windows Forms in C#. I have a method where I am adding MenuItem
s to the ContextMenu
and I implemented the event handlers for the MenuItem
s as below:
public void Form1_Load()
{
int index = 0;
ArrayList ar = new ArrayList();
ContextMenu cm = new ContextMenu();
cm.Name = "Test";
MenuItem mi = new MenuItem("All");
mi.Click += new EventHandler(mi_All);
}
private void mi_All(object sender, EventArgs e)
{
// Here I want to access the arraylist and integer specified in above method
}
How can this be done? One possible solution is to declare the ArrayList
and int
as global variables, but I have a lot of variables like开发者_运维百科 this. If I take this approach, the variables will live until the form gets disposed. So this doesn't work. Is there another way of achieving this?
One option:
mi.Click += delegate (object sender, EventArgs e) { mi_All(sender, e, ar, index); };
...
private void mi_All(object sender, EventArgs e, ArrayList ar, int index)
{
...
}
Another:
mi.Tag = new object[] { ar, index };
...
private void mi_All(object sender, EventArgs e)
{
ArrayList ar = (ArrayList)((object[])((MenuItem)sender).Tag)[0];
int index = (int)((object[])((MenuItem)sender).Tag)[1];
...
}
The MenuItem
has a Tag
property that can be used to assign any custom information you like. So assign to this whatever you need to access when the event handler is invoked. In your example you would assign the integer index of the enu item and then inside the event handler use that as the index into the Form level ArrayList field.
精彩评论