1

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?

2 Answers 2

5

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);
}    
Sign up to request clarification or add additional context in comments.

2 Comments

Beat me to the punch, sir. +1 ;)
Halfway there! Can I get the object's index in the array from that?
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.