1

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'.'

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry it didn't work, I put it in my foreach loop, and would get this exception: System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index'
I figured it out, I was putting it in the wrong place, I put it in the MouseClick event, and now it works, Thank so much Jan
Welcome. If it works for you, don't forget to close the question. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.