Remove Dynamic Picturebox

0

I have an "Add" button which when clicked opens a screen for the user to select an image, that image is added to a flowLayoutPanel. A dynamic "Remove" button is added to the pictureBox, when that button is clicked the pictureBox should be removed.

I have this method:

private void AdicionarImagem()
        {
            try
            {
                DialogResult dr = new DialogResult();
                OpenFileDialog openDialog = new OpenFileDialog();
                openDialog.Title = "Localizar Foto";
                openDialog.Filter = "Arquivo (*.PNG)|*.PNG|Arquivo (*.JPG)|*.JPG|Arquivo (*.JPEG)|*.JPEG| All files(*.*) | *.* ";
                openDialog.CheckFileExists = true;
                openDialog.CheckPathExists = true;
                openDialog.InitialDirectory = "C:";
                openDialog.RestoreDirectory = true;
                dr = openDialog.ShowDialog();
                string arquivo = openDialog.FileName;

                if (dr.ToString().ToUpper() == "OK")
                {
                    if (String.IsNullOrEmpty(arquivo))
                    {
                        MessageBox.Show("Arquivo inválido.", "Arquivo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    else
                    {
                        var pb = new PictureBox();
                        pb.SizeMode = PictureBoxSizeMode.AutoSize;
                        pb.BorderStyle = BorderStyle.Fixed3D;
                        pb.Image = Image.FromFile(arquivo);
                        pb.Tag = img.ToString();
                        img++;
                        pb.Parent = flpFotos;

                        var btn = new Button();
                        btn.BackColor = Color.Red;
                        btn.ForeColor = Color.White;
                        btn.FlatStyle = FlatStyle.Popup;
                        btn.Text = "Remover";
                        btn.Size = new Size(80, 31);
                        btn.Parent = pb;

                        btn.Click += delegate
                        {
                        };

                        pb.Show();
                        btn.Show();
                    }
                }

            }

            catch (Exception ex)
            {
                MessageBox.Show("Ocorreu o seguinte erro:\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

Images are coming with the correct tag, in sequence (the first pictureBox added gets 1, the second gets 2 and ...)

I wanted to know a way to remove the pictureBox by her tag. Thanks!

    
asked by anonymous 08.03.2018 / 21:13

1 answer

1

Just in the button event, you remove pb from flpFotos :

btn.Click += delegate
{
    flpFotos.Controls.Remove(pb);
};
    
08.03.2018 / 21:24