我从数据库中检索图像列表并在flowlayoutpanel中显示。
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++;
}
}
由于图片框是在flowlayoutpanel中自动生成的。任何人都知道如何通过点击图片框找到flowlayoutpanel中的图片框的索引?谢谢。
private void butns_Click(object sender, EventArgs e)
{
//code
}
答案 0 :(得分: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
private void butns_Click(object sender, EventArgs e)
{
var pictureBox = (PictureBox)sender;
int index = (int)pictureBox.Tag;
}