Muhammad Ali Dildar
Muhammad Ali Dildar

Reputation: 1527

Loading image into panel from database

My application saves image data in database and when loading information into form, it loads image into panel. This is working fine. But in case if user doesn't want to save image, I've inserted '0' in image field (varbinary) in database. While loading this information (0x00000000) from database it throws the following exception:

"Parameter is not valid."

Here I am giving some pieces of code:

Saving image in database:

if(user has selected an image)
{
   Byte[] imageBytes = File.ReadAllBytes(imagePatient);
   sqlCommand.Parameters.AddWithValue("Img", imageBytes); //Img is database column for images
}
else
{
   sqlCommand.Parameters.AddWithValue("Img", 0);
}

Loading image from database:

Byte[] imageData = new Byte[0];
imageData = (Byte[])(dataSet.Tables["Patients"].Rows[0]["Img"]);
MemoryStream stream = new MemoryStream(imageData);
panelImage.BackgroundImage = Image.FromStream(stream);

I've tried to put some check which will allow to load BackgroundImage if and only if data is not of the zeros form.

Please tell me how can I solve this issue?

Upvotes: 0

Views: 1433

Answers (1)

msigman
msigman

Reputation: 4524

I would store a NULL instead of 0.

if(user has selected an image) 
{ 
   Byte[] imageBytes = File.ReadAllBytes(imagePatient); 
   sqlCommand.Parameters.AddWithValue("Img", imageBytes); //Img is database column for images 
} 
else 
{ 
    sqlCommand.Parameters.Add("Img", SqlDbType.VarBinary, -1 );
    sqlCommand.Parameters["Img"].Value = DbNull.Value;
} 

And then use an if statement to check if it's non-null:

Byte[] imageData = new Byte[0]; 
imageData = (Byte[])(dataSet.Tables["Patients"].Rows[0]["Img"]); 
if(imageData != null)
{
    MemoryStream stream = new MemoryStream(imageData); 
    panelImage.BackgroundImage = Image.FromStream(stream); 
}

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx

Upvotes: 1

Related Questions