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

时间:2013-04-01 17:39:40

标签: 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)
{          
  //???
}

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:1)

另一个建议 - 创建一个继承自PictureBox的自定义类。它将有一个额外的Index属性。你可以在这两行之间设置它:

txtTeamNames[i].Visible = true;
//assign the index here
txtTeamNames[i].Click += new EventHandler(this.clcikeventhandle);
像这样:

txtTeamNames[i].Index = i;

然后在处理程序中:

void clickEventHandle(object sender, EventArgs e)
{ 
  PictureBox pbox = sender As PictureBox;
  int index = pbox.Index();
  string name = pbox.Name();
}

您保留相同的变量范围,如果您担心它可能会有用。如果您可以将txtTeamNames的范围升级到班级,请参阅another answer by Hossein Narimani Rad

答案 2 :(得分:0)

namespace your_name_project
{
    public partial class Form_Begin : Form
    {
        PictureBox[] pictureBoxs = new PictureBox[6];
        public Form_Begin()
        {
            InitializeComponent();
            pictureBoxs[0] = pictureBox1; pictureBoxs[1] = pictureBox2; pictureBoxs[2] = pictureBox3;
            pictureBoxs[3] = pictureBox4; pictureBoxs[4] = pictureBox5;   pictureBoxs[5] = pictureBox6;     
        }
//continue 
        List<PictureBox> pictureBoxes = new List<PictureBox>();

            private void buttonX1_Click(object sender, EventArgs e)
            {
                for (int i = 0; i <3; i++)
                {
                    pictureBoxs[i].Image =your_name_project.Properties.Resources.image_1;// load image1 and Image_2from resource in property of picturebox  
                }
                for (int i = 3; i < 6; i++)
                {
                    pictureBoxs[i].Image = your_name_project.Properties.Resources.Image_2;
                }
            } 
        }
}