Please pardon my knowledge on C# as I am very new to it,I am unable to insert a record in SQL and getting the below error while insert image to SQL. Error :
Object reference not set to an instance of an object.
x
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] img = ms.ToArray();
if (img == null)
{
com.Parameters.AddWithValue("@img", null);
}
else
{
com.Parameters.AddWithValue("@img", img);
}
If i select a image and insert it inserts successfully, but if i do not select an image it throws the above error. Please help!!
Advertisement
Answer
Try testing that PictureBox1.Image exists before referencing it, like this:
if (pictureBox1.Image != null)
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
byte[] img = ms.ToArray();
com.Parameters.AddWithValue("@img", img);
}
else
{
com.Parameters.Add("@img", SqlDbType.VarBinary, 0).Value = DbNull.Value;
}
EDITED to include comment by GarethD