c# -点击事件发送值

本文关键字:事件 -点 | 更新日期: 2023-09-27 18:16:41

我使用for循环将值添加到PictureBox数组中,并为每个值绑定一个单击事件。我正在寻找一种方法获得一个图片框点击后的数据。因为它是一个数组,我正在考虑发送循环计数器的值,它将确定哪个被点击。

我的代码是这样的:

PictureBox[] picboxes = new PictureBox[result];
for (int i = 0; i < results; i++)
{
    picboxes[i] = new PictureBox();
    picboxes[i].ImageLocation = @FormIni.RetRes((i * 5) + 5 + i);
    picboxes[i].Click += new System.EventHandler(PictureBoxes_Click);
}
private void PictureBoxes_Click(object sender, EventArgs e)
{
    label1.Text = "here I need the value of the picboxes[i] image location";
}

这看起来很愚蠢,但我想到了这样的东西:

picboxes[i].Click += new System.EventHandler(PictureBoxes_Click(i))

private void PictureBoxes_Click(object sender, EventArgs e, int i)

简而言之:当我点击在一个数组中创建的PictureBox通过代码,我如何得到它的值(在点击事件处理程序)?

编辑!

很抱歉在提出这个问题之后才找到它,但我已经找到了这个解决方案,它可能适用于我的情况,对吗?

c# -点击事件发送值

try do do this

PictureBox[] picboxes = new PictureBox[result];
for (int i = 0; i < results; i++)
{
    picboxes[i] = new PictureBox();
    picboxes[i].Name = (i+1).ToString();
    picboxes[i].ImageLocation = @FormIni.RetRes((i * 5) + 5 + i);
    picboxes[i].Click += new System.EventHandler(PictureBoxes_Click);
}
private void PictureBoxes_Click(object sender, EventArgs e)
{
    PictureBox p = (PictureBox)sender;
    string j = p.Name;
    label1.Text = j;
} 

您可以使用以下(匿名方法)lambda表达式

 picboxes[i].Click += (sender, eventArguments) => PictureBoxes_Click(sender, eventArguments, i);

使用标签

PictureBox[] picboxes = new PictureBox[result];
for (int i = 0; i < results; i++)
{
    picboxes[i] = new PictureBox();
    picboxes[i].Tag = (i+1).ToString();
    picboxes[i].ImageLocation = @FormIni.RetRes((i * 5) + 5 + i);
    picboxes[i].Click += new System.EventHandler(PictureBoxes_Click);
}
private void PictureBoxes_Click(object sender, EventArgs e)
{
    PictureBox p = (PictureBox)sender;
    string j = p.tag.tostring();
    label1.Text = j;
}