SQL Server 2014 中的 NullReferenceException

NullReferenceException in SQL Server 2014

我想将复选框列表数据保存在数据库中。我在 SQL 中创建了一个名为 'tblSubject' 的 table,并在 web.config 中创建了连接字符串。但是我仍然得到错误:

NullReferenceException was unhandled by user code
object reference not set to an instance of an object.

这是c#中的代码:

 private void PopulateSubjects()
{
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager
                .ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "select * from subjects";
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    ListItem item = new ListItem();
                    item.Text = sdr["Subject"].ToString();
                    item.Value = sdr["Id"].ToString();
                    item.Selected = Convert.ToBoolean(sdr["IsSelected"]);
                    chbox.Items.Add(item);
                }
            }
            conn.Close();
        }
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager
                .ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "update subjects set IsSelected = @IsSelected" +
                              " where Id=@Id";
            cmd.Connection = conn;
            conn.Open();
            foreach (ListItem item in chbox.Items)
            {
                cmd.Parameters.Clear();
                cmd.Parameters.AddWithValue("@IsSelected", item.Selected);
                cmd.Parameters.AddWithValue("@Id", item.Value);
                cmd.ExecuteNonQuery();
            }
            conn.Close();
        }
    }

}

在Web.config中:

 <connectionStrings>
  <add name=" constr" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;
  Initial Catalog = dbtblSubject; Integrated Security = true" providerName="System.Data.SqlClient" />
 </connectionStrings>

如有任何帮助,我们将不胜感激。

删除Web.config中的white space:

<add name=" constr" ...

<add name="constr" ...

首先,您应该查看堆栈跟踪以了解出现空引用的位置。

看来你的思路是正确的,认为连接字符串是这个异常的原因。如果您查看 Web.config,连接字符串的名称是“constr”,开头有一个额外的 space。这与您的代码不匹配:

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

删除 Web.Config 中连接字符串名称中的第一个 space,您的代码可能会起作用。