0

I have downloaded this PictureBox ImageArray
then I've added a button which will add all it's image to sql server 2005

this is the code:

private System.Windows.Forms.PictureBox[] imgArray2;
string c_string = "server=.\\sqlexpress;database=Blue;trusted_connection=true";


for (int i = 0; i < NumOfFiles; i++)
{
    imgArray2[i].Image = Image.FromFile(imgName[i]);
    string name = imgName[i].Substring(imgName[i].LastIndexOf(@"\") + 1, imgName[i].Length - imgName[i].LastIndexOf(@"\") - 1);
    MemoryStream mstr = new MemoryStream();
    imgArray2[i].Image.Save(mstr, imgArray2[i].Image.RawFormat);
    byte[] arrImage = mstr.GetBuffer();
    string cmd = "insert into Images (ImagePart" + i + "Name, ImagePart" + i + ") values (@PName, @Pic)";

    SqlConnection c = new SqlConnection(c_string);
    SqlCommand comm = new SqlCommand(cmd, c);
    comm.Parameters.Add(new SqlParameter("@PName", SqlDbType.VarChar, 40)).Value = name;
    comm.Parameters.Add(new SqlParameter("@Pic", SqlDbType.Image)).Value = arrImage;

    try
    {
        c.Open();
        comm.ExecuteNonQuery();
    }
    catch (System.Data.SqlClient.SqlException err)
    {
        MessageBox.Show(err.Message);
    }
    finally
    {
        c.Close();
    }

}

I've added an imgArray2[] so the image from imgArray[] won't changes and even though I'm using imgArray[] it still throwing the Null error.

The error info highlights the imgArray2[i].Image = Image.FromFile(imgName[i]);
it shows nullreferenceexception was unhandled - Object reference not set to an instance of an object.

1
  • 2
    This kind of problem can be solved by using the debugger to track down where the null reference occurred. Please don't make others debug your code for you. Commented Feb 27, 2012 at 21:01

3 Answers 3

3

The imgArray value and it's contents are never initialized. It needs to be an array capable of holding at least NumFiles items and each item needs to be initialized.

imgArray2 = new System.Windows.Forms.PictureBox[NumFiles];
for (int i = 0; i < NumOfFiles; i++)
  imgArray2[i] = new System.Windows.Forms.PictureBox();
Sign up to request clarification or add additional context in comments.

1 Comment

that and this imgArray2[i] = new System.Windows.Forms.PictureBox(); after that will do the work
1

You need to instantiate your System.Windows.Forms.PictureBox[] imgArray2 array before using it.

Comments

0

I just had a brief look and it looks like your imgArray2 is never instantiated... you just declared a variable and tried to access it

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.