检测鼠标单击控件数组

时间:2009-09-25 19:35:56

标签: c# windows-forms-designer

我在运行时向表单添加一个Panel对象数组(后面又包含其他项)。然后,我正在为循环内的每个面板分配一个click事件,如下所示:

pnlInstrument[index].Click += pnlInstrument_Click;

空单击功能如下所示:

private void pnlInstrument_Click(object sender, EventArgs e)
{

}  

事件正确触发,但如何判断单击了哪个面板?

2 个答案:

答案 0 :(得分:5)

使用事件方法的sender参数..

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

编辑:有关获取索引的评论..

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

答案 1 :(得分:0)

为什么不:

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