Skip to main content
 首页 » 编程设计

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

2024年02月13日12daizhj

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

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()); 
}