繁体   English   中英

SQL Server 2014中的NullReferenceException

[英]NullReferenceException in SQL Server 2014

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

用户代码未处理NullReferenceException
你调用的对象是空的。

这是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.configwhite space

<add name=" constr" ...

<add name="constr" ...

首先,您应该查看堆栈跟踪中是否存在nullreference。

您似乎在正确的轨道上,认为连接字符串是导致此异常的原因。 如果您查看Web.config,则连接字符串的名称为“ constr”,开始处有多余的空格。 这与您的代码不匹配:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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