Reputation: 65
I'm trying to create several objects and add them into an array which I can do but then I would like to have one event for all the objects. For example I have 50 picture boxes in an array that are created dynamically and I need to get the picture from the one I click. How do I go about doing this without making 50 seperate events?
Upvotes: 2
Views: 2576
Reputation: 124682
You hook up an event handler to Click
event of each PictureBox
. Use the sender
argument to obtain a reference to the specific PictureBox
that was clicked (that's what sender
is there for if you didn't know; whichever object raised the event will get passed to the handler as the sender
parameter).
private void HookUpEventHandlers()
{
var someListOfPicBoxes = GetPicBoxList();
foreach(var p in someListOfPicBoxes)
{
p.Click += p_Click;
}
}
private void p_Click(object sender, EventArgs e)
{
// this is the PictureBox that was clicked
var pb = (PictureBox)sender;
}
Upvotes: 7
Reputation: 44931
You create one event handler and add it to each of the items that you create:
Add the items:
for (int nI = 0; nI < 50; nI++)
{
PictureBox oBox;
oBox = new PictureBox();
oBox.Click += pictureBox_Click;
// Add to your array
}
Add the eventhandler:
private void pictureBox_Click(object sender, EventArgs e)
{
// Get a local reference to the box that was clicked
PictureBox oBox = sender as PictureBox;
}
Upvotes: 0