Picturebox Dinâmico

Asked

Viewed 148 times

2

I have a table called "Subordinate" where users are registered with their respective photos. I have a form and need to display the photos of all 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 registered photo should be shown in a different Picturebox and not being able to do it. How do I do that?

1 answer

0


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

Place a Flowlayoutpanel wherever the photos appear, and then change your Reader loop:

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

}
  • It worked perfectly, thanks. But what if I want to put the Click event in each Picturebox?

  • I changed again by placing the event click. If you need anything else, opens a new question that gets better =]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.