C# - 发送值的Click事件

问题描述 投票:3回答:3

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

编辑!

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

c# picturebox
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;
} 

0
投票

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

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

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;
} 
© www.soinside.com 2019 - 2024. All rights reserved.