简体   繁体   中英

c# load images from datatable to picturebox

I use the following code in order to load a datatable to my label string , it works.

Issue: similarly i'm trying to load images from a datatable to a picturebox. I've written some code but don't know what I should do for continuing.

pc[i].image=dt.Rows[i][1]

Any help will be appreciated.

    private void button1_Click(object sender, EventArgs e)
    {
        Label[] lbl = { label1, label2, label3, label4, label5};
        PictureBox[] pc = { pictureBox1, pictureBox2, pictureBox3, pictureBox4, pictureBox5 };

        DataTable dt = new DataTable();
        dt.Columns.Add("degree", typeof(string));
        dt.Columns.Add("icon", typeof(Image));
        {
            ----
            dt.Rows.Add(new object[] { a, b });
        }

        for (int i = 0; i < 10; i++)
        {
            lbl[i].text= dt.Rows[i][0].ToString();
            pc[i].image=dt.Rows[i][1]?????
        }
    }
    ```

Assuming you are storing images as bytes in database. Then you need to convert the bytes into image.

byte[] ba = (byte[])dt.Rows[i][1];
System.IO.MemoryStream ms = new System.IO.MemoryStream(ba);
Image img = Image.FromStream(ms);
pc[i].Image = img;

Try explicitly cast as Image...

DataTable dt = new DataTable();
dt.Columns.Add("degree", typeof(string));
dt.Columns.Add("icon", typeof(Image));
{
    dt.Rows.Add(new object[] { "test", Image.FromFile(@"c:\atom-icon.png") });
}

PictureBox[] pc = { pictureBox1 };
pc[0].Image = (Image)dt.Rows[0][1];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM