获取被点击的图片框数组的索引 [英] Get the index of array of picturebox clicked

查看:29
本文介绍了获取被点击的图片框数组的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating some picturebox dynamically and click event for picturebox as follows

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

当有人点击任何图片框时,我如何找到它的数组索引和名称?

When someone clicks on any picture box, how do I find its array index and name?

void clickEventHandler(object sender, EventArgs e)
{          
  //???
}

推荐答案

您可以通过 sender 参数访问 PictureBox.所以试试这个:

You can access the PictureBox via the sender argument. So try this:

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

但是如果您对在类范围内声明该数组不满意,您可以尝试这种方法:

But if you are not happy with declaring that array in the class scope you can try this approach:

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

这篇关于获取被点击的图片框数组的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆