Alexander Yap
Alexander Yap

Reputation: 58

C# Index of PictureBox in FlowLayoutPanel

I have retrieve list of images from database and display in 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++;
                }
            }

Since the picturebox is auto generate in the flowlayoutpanel. Anyone know how to find the index of the picturebox in the flowlayoutpanel by onclick the picturebox? Thank you.

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

Upvotes: 0

Views: 3460

Answers (1)

Alexander Petrov
Alexander Petrov

Reputation: 14251

You can get the index from the collection of the parent control.
Be careful, index depends on all the controls placed in the collection.

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

Another way is to use the Tag property.

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

Upvotes: 2

Related Questions