Ruchi
Ruchi

Reputation: 146

C# Error : Unable to insert record in SQL

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.

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!!

Upvotes: 1

Views: 151

Answers (3)

Sagar Kumar
Sagar Kumar

Reputation: 51

first, you need to make a new condition to check is file selected or not.here are code below:

if pictureBox1.hasfile == true 
{
                    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);
                    }
}

because you are not selecting any file thats why it throwing exception on runtime

Upvotes: 0

Jon Roberts
Jon Roberts

Reputation: 2282

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

Upvotes: 2

Athanasios Kataras
Athanasios Kataras

Reputation: 26450

Change this:

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);
}

To this

MemoryStream ms = new MemoryStream();
pictureBox1?.Image?.Save(ms, pictureBox1?.Image?.RawFormat);
byte[] img = ms.ToArray();
com.Parameters.AddWithValue("@img", (object)img ?? DBNull.Value);

Upvotes: 3

Related Questions