我正在动态创建一些图片框并为图片框点击事件如下
Image myImage = Image.FromFile("image/Untitled6.png");
PictureBox[] txtTeamNames = new PictureBox[5];
for (int i = 0; i < txtTeamNames.Length; i++)
{
var txt = new PictureBox();
txtTeamNames[i] = txt;
txtTeamNames[i].Image = myImage;
txtTeamNames[i].Height = 53;
txtTeamNames[i].Width = 48;
this.panel1.Controls.Add(txtTeamNames[i]);
txtTeamNames[i].Visible = true;
txtTeamNames[i].Click += new EventHandler(this.clcikeventhandle);
}
当有人点击任何图片框时,我如何找到它的数组索引和名称?
void clickEventHandler(object sender, EventArgs e)
{
//???
}
最佳答案
您可以通过sender
参数访问PictureBox
。所以试试这个:
PictureBox[] txtTeamNames;
void YourMethod()
{
Image myImage = Image.FromFile("image/Untitled6.png");
txtTeamNames = new PictureBox[5];
//The same as your code
}
void clcikeventhandle(object sender, EventArgs e)
{
int index = txtTeamNames.IndexOf(sender As PictureBox);
}
编辑:方法 #2
但是如果您不喜欢在类范围内声明该数组,您可以尝试这种方法:
//Same as your code
for (int i = 0; i < txtTeamNames.Length; i++)
{
//Save as your code
txtTeamNames[i].Tag = i; // ADD THIS LINE
}
然后:
void clcikeventhandle(object sender, EventArgs e)
{
int index = int.Parse((sender as PictureBox).Tag.ToString());
}
关于c# - 获取点击的图片框数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15748429/