【问题标题】:Treeview throwing NullReferenceException in winforms [duplicate]Treeview在winforms中抛出NullReferenceException [重复]
【发布时间】: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


【解决方案1】:

你还没有给 else if 中的 mdt 变量赋值。

在第一个分支中,您将其分配为

mdt = row["CountryName"].ToString().Trim();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 2020-11-17
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多