简体   繁体   中英

Detecting Mouse Click on an Array of Controls

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM