Dynamic PictureBox

2

I have a table called "Subordinate" where users with their respective photos are registered. I have a form and I need to display the photos of all the registered users.

For this I have the following method:

private void ListarImagens()
{
    strSql = "Select Imagem from Subordinado";

    using (SqlConnection sqlCon = new SqlConnection(strCon))
    {
        SqlCommand cmd = new SqlCommand(strSql, sqlCon);

        try
        {
            sqlCon.Open();

            SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                fotoArray = (byte[])reader["Imagem"];
                MemoryStream ms = new MemoryStream(fotoArray);
                pic1.Image = Image.FromStream(ms);


            }
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        finally
        {
            sqlCon.Close();
        }
    }
}

Each photo must be shown in a different PictureBox and can not do it. How do I do this?

    
asked by anonymous 08.11.2017 / 20:32

1 answer

0

Considering that you are using winforms and that your code is in the form itself:

Place a FlowLayoutPanel wherever the photos appear, and then change the loop of your reader:

while (reader.Read())
{
    fotoArray = (byte[])reader["Imagem"];
    MemoryStream ms = new MemoryStream(fotoArray);
    PictureBox pb = new PictureBox(); //Cria um novo picturebox
    pb.Image = Image.FromStream(ms); //carrega a imagem
    pb.SizeMode = PictureBoxSizeMode.Zoom; //define as propriedades do picturebox
    pb.Parent = flowLayoutPanel1; //Coloca o picturebox dentro do FlowLayoutPanel
    pb.Width = 250; //define a largura
    pb.Height = 300; //define a altura

    //Para adicionar um toolTip, basta coloca-lo no Form e usar:
    toolTip1.SetToolTip(pb, "Descrição da imagem");


    //Para criar um evento no pictureBox
    pb.Click += (s, arg) => { 

            //Faz o evento Click
            //s é o seu sender (picturebox que disparou o evento)
            //arg é o EventArgs

    };


    pb.Show(); //exibe o controle

}
    
08.11.2017 / 22:28