我想尝试在树视图中实现数据库记录,如父和子(表)。在运行期间,我的连接字符串出错了。
错误行: -
string connectionstring = ConfigurationManager.ConnectionStrings["Data Source=ASDF;Initial Catalog=dbtree;Integrated Security=True"].ConnectionString;
错误是: -
System.NullReferenceException was unhandled by user code
Object reference not set to an instance of an object.
注意:在我的数据库中没有字段为空
代码: -
string connectionstring = ConfigurationManager.ConnectionStrings["Data Source=ASDF;Initial Catalog=dbtree;Integrated Security=True"].ConnectionString;
SqlConnection mycon = new SqlConnection(connectionstring);
mycon.Open();
SqlCommand mycmd = new SqlCommand("Select * from tbl_Parent", mycon);
SqlDataReader dr = mycmd.ExecuteReader();
mycmd.Dispose();
string[,] ParentNode = new string[100, 2];
int count = 0;
while (dr.Read())
{
ParentNode[count, 0] = dr.GetValue(dr.GetOrdinal("Parent_id")).ToString();
ParentNode[count++, 1] = dr.GetValue(dr.GetOrdinal("Parent_name")).ToString();
}
dr.Close();
答案 0 :(得分:4)
替换
string connectionstring = ConfigurationManager.ConnectionStrings["Data Source=ASDF;Initial Catalog=dbtree;Integrated Security=True"].ConnectionString;
使用
string connectionstring = "Data Source=ASDF;Initial Catalog=dbtree;Integrated Security=True";
或使用连接字符串名称
string connectionstring = ConfigurationManager.ConnectionStrings["Name here"].ConnectionString;
更新:如下面的评论者建议,您可以在web.config文件中找到连接字符串的名称。
答案 1 :(得分:1)
您的连接字符串行不正确。它正在web.config中寻找一个名为
的节点"Data Source=ASDF;Initial Catalog=dbtree;Integrated Security=True".
由于该节点(显然)不存在,因此返回null
并且您将获得异常。
我怀疑你只是想要:
string connectionstring = "Data Source=ASDF;Initial Catalog=dbtree;Integrated Security=True";
但没有更多的背景,我无法确定。