2015-11-12 36 views
0

我从数据库中检索图像列表并在flowlayoutpanel中显示。FlowLayoutPanel中PictureBox的C#索引

int i = 1; 
      byte[] imgData; 
      SqlConnection con = new SqlConnection(localdb); 
      con.Open(); 
      SqlCommand cmd = new SqlCommand("SELECT image FROM Image", con); 
      SqlDataReader rdr = cmd.ExecuteReader(); 

      while (rdr.Read()) 
      { 
       imgData = (byte[])(rdr["image"]); 
       using (MemoryStream ms = new MemoryStream(imgData)) 
       { 
        System.Drawing.Image photo = Image.FromStream(ms); 
        pbName[i] = new PictureBox(); 
        pbName[i].Image = photo; 
        pbName[i].SizeMode = PictureBoxSizeMode.CenterImage; 
        pbName[i].Parent = this.flowLayoutPanel1; 
        pbName[i].Click += new EventHandler(butns_Click); 
        i++; 
       } 
      } 

由于picturebox是在flowlayoutpanel中自动生成的。任何人都知道如何通过点击图片框来找到flowlayoutpanel中picturebox的索引?谢谢。

private void butns_Click(object sender, EventArgs e) 
{ 
    //code 
} 

回答

1

您可以从父控件的集合中获取索引。
要小心,索引取决于放置在集合中的所有控件。

private void butns_Click(object sender, EventArgs e) 
{ 
    var pictureBox = (PictureBox)sender; 
    int index = flowLayoutPanel1.Controls.GetChildIndex(pictureBox); 
} 

另一种方法是使用Tag属性。

pbName[i].Tag = i; // puts index to tag 
​​