2013-04-01 33 views
1

我创建动态的一些图片框和图片框单击事件如下获取图片框的数组的索引点击

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

您可以通过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()); 
} 
+0

+1。现在只涉及范围。如果OP在课堂级声明'txtTeamNames',这就是答案。 – Neolisk

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

+0

我很想知道如何创建一个完全符合我答案的链接?怎么可能?谢谢。 –

+0

@HosseinNarimaniRad:您的答案下方有一个共享链接。 :) – Neolisk

+0

哇!看来我从来没有注意到它! –

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