简体   繁体   中英

nullreferenceexception was unhandled - c#

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.

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

您需要先实例化System.Windows.Forms.PictureBox[] imgArray2数组,然后再使用它。

我只是看了一下,看起来您的imgArray2从未实例化……您只是声明了一个变量并尝试访问它

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM