Reputation: 1733
I can't find solution similar to what I expect to happen. How can I add additional parameter to the method i want to subscribe to?
Suppose this line below is the code that subscribe to mouseover:
Panel cagePanel = new Panel();
cagePanel.MouseHover += new EventHandler(frmMain_MouseHover);
void frmMain_MouseHover(object sender, EventArgs e){
// I wanna add some 'int index' parameter after 'e' variable)
}
What I really want is just like this:
void frmMain_MouseHover(object sender, EventArgs e, int index){
strings[index] = "bla bla bla";
}
Upvotes: 0
Views: 91
Reputation: 1503419
I can't find solution similar to what I expect to happen. How can I add additional parameter to the method i want to subscribe to?
You can't. How would the code raising the event (Panel.OnMouseHover
or whatever) know what value to provide?
If you know at the time you subscribe the event, you can use a lambda expression to basically delegate the call, providing the extra information:
// 10 is just an example here - use whatever value you want for index
cagePanel.MouseHover += (sender, args) => frmMain_MouseHover(sender, args, 10);
EDIT: To iterate over each control in an array and subscribe an appropriate handler for each, you could use something like this:
for (int i = 0; i < array.Length; i++)
{
// See http://tinyurl.com/3b2hoft for reasons behind the copy
int index = i;
array[i].MouseHover += (s, args) => frmMain_MouseHover(s, args, index);
}
I would personally try to avoid needing this, however - can you not detect the index via the sender
part, potentially using Array.IndexOf
?
Upvotes: 2
Reputation: 152634
You can't, but if the extra data you need is related to what sent the event, you could use the sender
value. For example, if you want to know the index in a list of controls of the item that raised the event, you could do something like:
int i = controlList.IndexOf(sender);
Upvotes: 2