Passing a Variable to an Event in .NET
For example I have a list of picture boxes that raise an event once the cursor hover over them. Yet I n开发者_如何转开发eed somehow not only to rise this event, but also to pass the "i" variable, so that I would know which picturebox has the cursor over it.
for (int i = 0; i < 25; i++)
{
....
pbList.Add(new PictureBox());
pbList[i].MouseHover += new System.EventHandler(this.beeHideInfo);
//// need to pass "i" here
}
and
private void beeShowInfo(object sender, EventArgs e)
{
lb_beeInfo.Text = "You are hovering over: "+beeList[i].name;
/// need to get this "i"
}
Any ideas?
You cannot pass variables to an event.
Besides, the necessary variable has already been passed to you: sender
.
sender
is a reference to the object which raised the event. In your case, it's a reference to the PictureBox that raised the event.
The object sender
parameter is the PictureBox
sending the event. If you need to associate something with that object, you can use its Tag
member:
for (int i = 0; i < 25; i++)
{
....
pbList.Add(new PictureBox() { Tag = beeList[i] });
pbList[i].MouseHover += new System.EventHandler(this.beeHideInfo);
}
and
private void beeShowInfo(object sender, EventArgs e)
{
PictureBox pb = (PictureBox)sender;
Bee b = (Bee)pb.Tag;
lb_beeInfo.Text = "You are hovering over: "+b.name;
}
Assuming pbList and beelist contain related items in the same order, you can do something like beeList[ pbList.IndexOf(sender) ].name
You could you do something like:
for (int i = 0; i < 25; i++)
{
...
pbList.Add(new PictureBox());
var index = i;
pbList[i].MouseHover +=
delegate
{
lb_beeInfo.Text = "You are hovering over: "+beeList[index].name;
};
}
I.e. use an anonymous method.
As John Saunders says, there is an easier solution.
The easiest way to do this is use an anonymous function to explicitly pass the PictureBox
or index instance into the handler.
for (int i = 0; i < 25; i++)
{
....
var box = new PictureBox();
pbList.Add(box);
box.MouseHover += delegate { this.beeShowInfo(box); }
}
private void beeShowInfo(PictureBox box)
{
lb_beeInfo.Text = "You are hovering over: "+box.Name;
}
another way might be if you create a Custom Picture Box
class CustomPictureBox : PictureBox
{
public int id;
public CustomPictureBox(int ID)
{
id = ID;
}
}
firt place a GLOBAL id to parent and each time if a CustomPicureBox is clicked get the ID than everywhere you want to make changes to Clicked CustomPicutreBox test it
foreach(CustomPicutreBox i in Control.controls)
{
if(i.ID == sender.ID)
doWhatEveryYouWant();
}
}
精彩评论