简体   繁体   中英

How to load data with images from database into DataGridView?

I'm trying to load data from database into dataGridView, and when a row is selected, the records would get displayed on other controls, it works but not as expected, specially when there is null values on the image column, I don't know what to do next

Here's my table structure:

TABLE TblProduct
[ProductID]   INT            IDENTITY (1, 1) NOT NULL,
[ProductType] INT            NOT NULL,
[Description] NVARCHAR (MAX) NULL,
[Price]       MONEY          NULL,
[Image]       IMAGE          NULL,

Here's my Retrieve() method:

private void Retrieve()
{
    dataGridView1.Rows.Clear();

    string sql = "SELECT * FROM TblProduct";
    cmd = new SqlCommand(sql, connection);
    connection.Open();
    adapter = new SqlDataAdapter(cmd);
    adapter.Fill(dt);       

    foreach (DataRow row in dt.Rows)
    {                
        dataGridView1.Rows.Add(row[0].ToString(), row[1].ToString(), row[2].ToString(), Convert.ToDecimal(row[3]), row["Image"]);
    }
    connection.Close();
    dt.Rows.Clear();
}

Here's my MouseClick event:

private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
    typeTxt.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
    descriptionTxt.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
    priceTxt.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
    pictureBox1.Image = (Image)dataGridView1.SelectedRows[0].Cells["Image"].Value;            
}

Here's the exceptions I get when selecting a row on the dataGridView that has an image

System.InvalidCastException: 'Unable to cast object of type 'System.Byte[]' to type 'System.Drawing.Image'.'

And when selecting a row on the dataGridView that has no image

System.InvalidCastException: 'Unable to cast object of type 'System.DBNull' to type 'System.Drawing.Image'.'

You must create Image from byte array and also check DB nulls.

var value = dataGridView1.SelectedRows[0].Cells["Image"].Value
if(value != DBNull.Value)
{
   byte[] data = (byte[]) value;
   MemoryStream ms = new MemoryStream(data);
   pictureBox1.Image = Image.FromStream(ms);
}

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