Wednesday, June 12, 2013

"Parameter is not valid" Error when retrieving a Photo From SQL Server Database in C#

I have been banging my head trying to solve the error in a .Net app I am developing. The scenario is I am trying to capture an image using a webcam and displaying the image in a PictureBox control. Upon saving the image into the database, it runs smoothly. But after retrieving the image and displaying it into a PictureBox Control, this one pops up:
The image was not displayed. Debugging the code brings me to this line - picBox.Image = Image.FromStream(stream); - supposedly the culprit of the code. I have been googling around for solution but found nothing. It has been 2 days already. Fortunately, my brain cells started to fire up and inspected the code thoroughly and found out that the real culprit was with the insertion of the image into the database. The image is of VarBinary(MAX) datatype in my table by the way. Upon inspecting the code on the procedure when inserting image, I found out that the error is with the SQL Parameter declaration particularly the size of the datatype. Refer below code: Error Code: cmd.Parameters.Add(new SqlParameter("@Photo", SqlDbType.VarBinary, 100)).Value = ImageToByteArray(picBox.Image); Correct One: cmd.Parameters.Add(new SqlParameter("@Photo", SqlDbType.VarBinary, 2147483647)).Value = ImageToByteArray(picBox.Image); As you can see, the difference was the plugging of the datatype size in the SQL Parameter. Using the previous code, when saving the image into the database, it does not give an error during runtime but the resulted image (byte representation in the column of the table) is not correct. This is why when retrieving the image and displaying it into a PictureBox control gives a "Parameter Not Valid" error during runtime. The reason for this is the DataLength of the image being saved into the database is more than the 100 allowable size that was defined in the previous code. So to solve the issue, just modify the defined int size for the data type in the SQL paramneter. This solves the issue in my case. The result is a big SMILE!!! :-)