0

嗨,我正在尝试在树视图中实现数据库记录,如父子(表)。在运行时,我的连接字符串出现错误..

错误行:-

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();
4

2 回答 2

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 文件中找到连接字符串的名称。

于 2013-06-19T19:31:05.127 回答
1

您的连接字符串线不对。它正在 web.config 中寻找一个名为

"Data Source=ASDF;Initial Catalog=dbtree;Integrated Security=True".

由于该节点(显然)不存在,它正在返回null并且您遇到异常。

我怀疑你只是想要:

string connectionstring = "Data Source=ASDF;Initial Catalog=dbtree;Integrated Security=True";

但如果没有更多上下文,我无法确定。

于 2013-06-19T19:31:01.527 回答