【问题标题】:NullReferenceException Was Unhandled by user code in c#NullReferenceException 未被 c# 中的用户代码处理
【发布时间】:2016-06-19 19:39:21
【问题描述】:

当我们使用连接字符串NullReferenceException 创建连接时,发生了。错误是

用户代码未处理 NullReferenceException。

我的代码如下:

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

【问题讨论】:

  • 异常来自哪一行?你检查 FileUpload1.PostedFile 是否为空?
  • 您能否检查一下您的 app.config/web.config 文件中是否确实定义了带有键 constr 的连接字符串?

标签: c# sql asp.net nullreferenceexception


【解决方案1】:

您在

中使用 Data 而不是 @Data

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

所以这是正确的发送方式

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

【讨论】:

    【解决方案2】:

    您在发送变量 Data 时使用 @Data 变量在表中插入值只有

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

    【讨论】:

    • Sql 参数在没有@符号的情况下也能很好地工作,同时提供 sql 参数。
    【解决方案3】:

    您的代码很可能因为 FileUpload1.PostedFile 为空而引发 NullReferenceException。

    您可能在 UpdatePanel 中添加了 FileUpload。如果是,则需要使用 PostBackTrigger。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多