FlowLayoutPanel中PictureBox的C#索引

本文关键字:索引 PictureBox FlowLayoutPanel | 更新日期: 2023-09-27 18:21:39

我已经从数据库中检索到图像列表,并显示在流程布局面板中。

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

由于图片框是在流程布局面板中自动生成的。有人知道如何通过点击图片框在流程布局面板中找到图片框的索引吗?非常感谢。

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

FlowLayoutPanel中PictureBox的C#索引

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

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