2013-04-01 60 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; 
       } 
      } 
     } 
}