[英]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.config
的white 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.