Click here to Skip to main content
15,889,858 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
i need to get multiple image from sql server database and display it by auto created picturebox inside the flowlayout panel.but it displays the same image from first row of the table.

What I have tried:

C#
while (flowLayoutPanel.Controls.Count > 0)
            {
                flowLayoutPanel.Controls[0].Dispose();
            }
                con = new SqlConnection(@"Data Source=(local);Initial Catalog=hotel_manage;Integrated Security=True");
                con.Open();
                SqlCommand cmd = new SqlCommand("select * from item where cat_id=5", con);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                for (int i = 0; i < dt.Rows.Count;++i)
                {
                    PictureBox pic = new PictureBox();
                        con.Open();
                        SqlCommand cmmd = new SqlCommand("select image from item where cat_id=5", con);
                        Byte[] bytes = (Byte[])cmmd.ExecuteScalar();
                        MemoryStream ms = new MemoryStream(bytes);
                        pic.Image = Image.FromStream(ms);
                        pic.SizeMode = PictureBoxSizeMode.AutoSize;
                        this.flowLayoutPanel.Controls.Add(pic);
                }
        }
Posted
Updated 5-Jan-20 23:02pm
v3

You only ever retrieve one item from the database
C#
SqlCommand cmmd = new SqlCommand("select image from item where cat_id=5", con);
I think you need to remove the where clause from the Fill and then use the cat_id for each row as a parameter for the cmmd command
 
Share this answer
 
Well yes. That because you ask for the same image every time you go round the loop:
C#
SqlCommand cmmd = new SqlCommand("select image from item where cat_id=5", con);
If you replace the "5" with the value from your loop, then it will return different images.

But ... you have already retrieved all the images and they are in your DataTable - so why not use the values directly from there?
C#
byte[] bytes = (byte[]) dt.Rows[i]["image"];


And I'd use a foreach on the Rows instead of a for loop.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900