views:

58

answers:

2

I'm adding an array of Panel objects (which in turn contain other items) to a form at runtime. Then, I'm assigning a click event to each panel inside a loop like so:

pnlInstrument[index].Click += pnlInstrument_Click;

The empty click function looks like this:

private void pnlInstrument_Click(object sender, EventArgs e)
{

}

The event is triggering correctly, but how can I tell which panel was clicked?

+5  A: 

Use the sender parameter of the event method..

private void pnlInstrument_Click(object sender, EventArgs e)
{
    Panel panel = (sender as Panel); //This is the panel.
}

Edit: For comments of getting index..

private void pnlInstrument_Click(object sender, EventArgs e)
{
    Panel panel = (sender as Panel); //This is the panel.
    int panelIndex = Array.IndexOf(pnlInstrument, panel);
}
Quintin Robinson
Beat me to the punch, sir. +1 ;)
JustLoren
I blame it on over-exposure!
Quintin Robinson
Halfway there! Can I get the object's index in the array from that?
Works beautifully, thanks for the prompt response.
You got it, glad it works.
Quintin Robinson
A: 

Why not:

pnlInstrument[index].Click += pnlInstrument_Click;
pnlInstrument[index].Tag += index;

private void pnlInstrument_Click(object sender, EventArgs e)
{
    Panel pnl = (Panel)sender;
    int index = (int)pnl.Tag;
}
JDunkerley