Click here to Skip to main content
14,697,191 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a small isssure when I am going thru dgv with Image column and I need to change images in picture box beside dgv

I have this code on form_load and dgID_textchanged

if (image1.Image != null)

SqlCommand cmd22 = new SqlCommand("Image_proc", cs);
cmd22.CommandType = CommandType.StoredProcedure;
cmd22.Parameters.Add("@imgId", SqlDbType.Int).Value =
SqlDataAdapter adp = new SqlDataAdapter(cmd22);
DataTable dt = new DataTable();

    if (cs.State == ConnectionState.Closed)
    if (dt.Rows.Count > 0)

        MemoryStream ms = new MemoryStream((byte[])dt.Rows[0]["Image"]);

        image1.Image = Bitmap.FromStream(ms);


catch (Exception ex)
    MessageBox.Show(ex.Message, "Error",
          MessageBoxButtons.OK, MessageBoxIcon.Error);
    if (cs.State == ConnectionState.Open)

it all works great when there is a image in the cell of dgv but whene it is null value then I get Error Unable to cast object of type 'System.DBNull' to type 'System.Byte ... and I am stuck

[edit]Code block added - OriginalGriff[/edit]
Updated 22-Jun-13 6:11am

1 solution

Simple - check it.
if (dt.Rows.Count > 0)
    object o = dt.Rows[0]["Image"];
    Image im = null;
    if (o != DBNull.Value)
        MemoryStream ms = new MemoryStream((byte[])o);
        im = Bitmap.FromStream(ms);
    image1.Image = im;
shonezi 22-Jun-13 11:25am
now I get error on im = Bitmap.FromStream(ms) Cannot implicitly convert System.DrawingImage to User.Image

and on image1.Image = im I get cannot implicitly convert User.Image to System.drawing.Image :D :D :D
OriginalGriff 22-Jun-13 11:28am
Then change the types to match your code...
(Or preferably don't define classes with the same name as common .NET Framework classes)

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