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)
    image1.Image.Dispose();


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

try
{
    if (cs.State == ConnectionState.Closed)
        cs.Open();
    adp.Fill(dt);
    if (dt.Rows.Count > 0)
    {


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

        image1.Image = Bitmap.FromStream(ms);

        image1.Refresh();
    }

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


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]
Posted
Updated 22-Jun-13 6:11am
v2

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;
    image1.Refresh();
    }
   
Comments
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