简体   繁体   中英

NullReferenceException Was Unhandled by user code in c#

When we create a connection using connection string NullReferenceException is occurred. The error is

NullReferenceException is unhandled by user code.

My code is given below:

 protected void upload_Click(object sender, EventArgs e)
    {

        string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);

        string contentType = FileUpload1.PostedFile.ContentType;

        using (Stream fs = FileUpload1.PostedFile.InputStream)
        {
              using(BinaryReader br = new BinaryReader(fs))
              {
                  byte[] bytes = br.ReadBytes((Int32)fs.Length);


                      string constr =ConfigurationManager.ConnectionStrings["constr"].ConnectionString; 

                      using (SqlConnection con = new SqlConnection(constr))
                      {
                          string query = "insert into tblFiles values(@Name, @ContentType, @Data)";

                          using (SqlCommand cmd = new SqlCommand(query))
                          {
                              cmd.Connection = con;
                              cmd.Parameters.AddWithValue("@Name", filename);
                              cmd.Parameters.AddWithValue("@contentType", contentType);
                              cmd.Parameters.AddWithValue("Data", bytes);
                              con.Open();
                              cmd.ExecuteNonQuery();
                              con.Close();
                          }
                      }


              }
        }
        Response.Redirect(Request.Url.AbsoluteUri);
    }

You are using Data instead of @Data in

cmd.Parameters.AddWithValue("Data", bytes)

so this is the correct way to send

cmd.Parameters.AddWithValue("@Data", bytes);

Your are inserting the value in the table using @Data variable while you are sending the variable Data only

cmd.Parameters.AddWithValue("Data", bytes);  // error prompt code

cmd.Parameters.AddWithValue("@Data", bytes);  // correct Code

Most probably your code throwing NullReferenceException because of FileUpload1.PostedFile is null.

You may have added FileUpload inside UpdatePanel. If yes, then you need use PostBackTrigger.

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