【发布时间】:2015-08-27 19:35:38
【问题描述】:
它有值但不知道为什么仍然抛出nullRefrenceException。
这是我的带有 ChildView 的 treeView 代码。
我想用 DataSet 中的父子创建一个 treeView。
代码:
adp3 = new SqlDataAdapter("select country.CountryId , country.CountryName ,` city.CityId , city.CityName "+
" from Country as country join City as city on city.CountryId = country.CountryId order by cityid ", Program.con);
adp3.Fill(ds,"bb");
this.mtree.Nodes.Clear();
string mdt = "";
string mref = "";
string mtitle = "";
foreach (DataRow row in ds.Tables["bb"].Rows)
{
if (!row["Countryname"].ToString().Equals(mdt.Trim()))
{
TreeNode node = new TreeNode();
node.Name = (string)row["CountryId"].ToString().Trim();
node.Text = row["CountryName"].ToString();
this.mtree.Nodes.Add(node);
mdt = row["CountryName"].ToString().Trim();
mtitle = "";
}
else if (!row["CityName"].ToString().Equals(mtitle.Trim()))
{
TreeNode node2 = new TreeNode();
node2.Name = (string)row["CityId"].ToString().Trim();
node2.Text = row["CityName"].ToString().Trim();
this.mtree.Nodes[mdt.Trim()].Nodes.Add(node2);
mtitle = row["CityName"].ToString().Trim();
}
}
【问题讨论】:
-
请在您的问题中添加完整的错误消息。
-
知道哪条线也不会受伤。
-
对象引用未设置为对象的实例。在线 this.mtree.Nodes[mdt.Trim()].Nodes.Add(node2);
-
那么哪个表达式是空的?
mtree?mtree.Nodes?mdt?mtree.Nodes[mdt.Trim()]?mtree.Nodes[mdt.Trim()].Nodes? 方式在那个单一的语句中发生了太多事情......引入更多的局部变量,你会有更好的时间...... -
#jonSkeet this.mtree.Nodes[mdt.Trim()].Nodes.Add(node2);此表达式为空
标签: c# winforms treeview dataset