c# - 获取点击的图片框数组索引

标签 c# winforms

我正在动态创建一些图片框并为图片框点击事件如下

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/

相关文章:

c# - 带 GroupBy 的 Linq 表达式

c# - 如何在 xUnit 中设置测试优先级以及基于优先级运行选择性测试

c# - Facebook 登录未返回用户电子邮件

c# - ASP.NET Web API 在 IIS 中发布时不起作用?

c# - 使用重载的构造函数实例化泛型类型

.net - 按名称选择特定打印机 VB

C# - 将数据表绑定(bind)到reportviewer

c# - FileDialog.RestoreDirectory 属性实际上做了什么?

c# - Winform 数据绑定(bind)

c# - 如何使用 OpenXML 获取 Excel 工作表的使用范围?