我正在使用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解决方案,它可能适用于我的情况,对吗?
答案 0 :(得分: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;
}
答案 1 :(得分:0)
您可以使用以下(anoynomous方法)lambda表达式
picboxes[i].Click += (sender, eventArguments) => PictureBoxes_Click(sender, eventArguments, i);
答案 2 :(得分: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;
}