3

我正在使用 for 循环将值添加到 PictureBox 数组中,并将单击事件绑定到每个数组。我正在寻找一种在点击后获取 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 时,如何获取其值(在单击事件处理程序中)?

编辑!

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

4

3 回答 3

4

尝试这样做

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;
} 
于 2013-06-01T02:58:12.037 回答
0

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

 picboxes[i].Click += (sender, eventArguments) => PictureBoxes_Click(sender, eventArguments, i);
于 2013-06-01T02:36:16.970 回答
0

使用标签

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;
} 
于 2019-02-24T08:36:19.423 回答