How to find pictureBoxes in a form and add a specific EventHandler to them

I want to have a photo album, which, when I click on any picture, goes into another form to edit this image.

Now I have several images in the form with names such as PB0, PB1, PB2, ...

and such a method

private void msgShow(int id)
{
    MessageBox.Show(id.ToString());
}

when I add an event handler to two pictures like this

PB11.Click += new EventHandler((sender2, e2) => msgShow(3));
PB12.Click += new EventHandler((sender2, e2) => msgShow(4)); 

when I click PictureBox1 (PB1) messageBox shows

3

and when I click PictureBox2 (PB2), the message Box shows

4

this was true since I added 18 new pictures and used this code for this

for (int i = 0; i <= 19; i++)
{
    ((PictureBox)Form2.ActiveForm.Controls.Find("PB" + i, true)[0]).Click += new EventHandler((sender2, e2) => msgShow(i));
}

now its wrong, and when I click on every image that is displayed in the box, it is displayed

20

but I want to show unique numbers for each PictureBox

+4
2

. for

for (int i = 0; i <= 19; i++)
{
    var pictureBox = (PictureBox) Form2.ActiveForm.Controls.Find("PB" + i, true)[0];
    pictureBox.Tag = i;
    pictureBox.Click += (sender, args) =>
    {            
        msgShow((int)((sender as PictureBox).Tag));
    };
}

EDIT: ,

for (int i = 0; i <= 19; i++)
{
    var pictureBox = (PictureBox) Form2.ActiveForm.Controls.Find("PB" + i, true)[0];
    var productInfo = new ProductInfo
    {
        //This class is not mentioned into the question so I set example properties here eg.
       ImageName = "MyImage1.png",
       ImagePath = "C:\\Images\\"
       ...
    };
    pictureBox.Tag = productInfo;
    pictureBox.Click += (sender, args) =>
    {            
        msgShow((ProductInfo)((sender as PictureBox).Tag));
    };
}

msgShow ProductInfo i-e

private void msgShow(ProductInfo pr)
{
    using(var fr = new FormProduct())
    {      
       fr.pInfo = pr;
       fr.showDialog();
    }
}
+1

, int.

private void msgShow(ProductInfo pr)
{
    FormProduct fr= new FormProduct();
    fr.pInfo =pr;
    fr.showDialog();
}

for (int i = 0; i <= 19; i++)
{
    ((PictureBox)Form2.ActiveForm.Controls.Find("PB" + i, true)[0]).Click += new EventHandler((sender2, e2) => msgShow(list<ProductInfo>[i]));
}

Tag.

0

All Articles