SQL Server 2014中的NullReferenceException

节目21

我想将复选框列表数据保存在数据库中。我在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>

任何帮助将非常感激。

瓦加尔·艾哈迈德(Waqar Ahmed)

移除white space中的Web.config

<add name=" constr" ...

<add name="constr" ...

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章