c# - 为什么在winforms应用程序中点击treeview节点时会出现异常?

标签 c# winforms treeview

我的 TreeView 节点有问题。当我单击某些节点时,它会出现未处理的异常,并显示“对象引用未设置到对象的实例”。

我认为发生此异常是因为我在 mouseclick 事件中使用了 treeview.node.parent 和 treeview.node.firstnode 方法。

你能帮我解释一下为什么会发生这个异常吗?

我认为错误出现在这个片段中:

private void treeNode_AfterSelected(object o, TreeNodeMouseClickEventArgs e )
{
    // 
    if (e.Node.FirstNode != null && e.Node.Parent!=null && e.Node.Parent.Text == "Tables")
    {
        this.Controls.Remove(dg);
        this.dg= dal.showTable(e.Node.Text,e.Node.Parent.Parent.Text);
        this.dg.Location = new System.Drawing.Point(this.tr.Width + 1, this.menuStrip1.Height + 2);
        this.dg.Size = new System.Drawing.Size(n - dg.Location.X, 300);
        this.dg.BackgroundColor = System.Drawing.Color.White;
        this.tableName = e.Node.Text;    
        this.Controls.Add(dg);

    }

    else if (e.Node.FirstNode == null && e.Node.FirstNode.Text == "Tables")
    {
       dal.changeDatabase(e.Node.Text);

    }
}

抱歉,英语不好

最佳答案

如果您将单击父节点(第一级),然后调用

node.Parent.SomeMethod 你会得到 NullReference 异常,因为它的 Parent 是 null

进行一些验证以检查 Parent 是否不为空

if(node.Parent != null)
{
  // do stuff
}

node.FirstNode 的情况也是如此 - 如果该节点没有子节点,它将返回 null,因此还要对此进行验证

if(node.FirstNode != null)
{
  // do stuff
}

编辑: 在您的代码片段 e.Node.Parent.Parent 中,某些父项可以为 null,而 e.Node.FirstNode 可以为 null,因此您会以异常结束

if (e.Node.Parent != null && e.Node.Parent.Text == "Tables")
{
    this.Controls.Remove(dg);
    if(e.Node.Parent.Parent != null)
    { 
       this.dg= dal.showTable(e.Node.Text,e.Node.Parent.Parent.Text);
       this.dg.Location = new System.Drawing.Point(this.tr.Width + 1, this.menuStrip1.Height + 2);
       this.dg.Size = new System.Drawing.Size(n - dg.Location.X, 300);
       this.dg.BackgroundColor = System.Drawing.Color.White;
       this.tableName = e.Node.Text;    
       this.Controls.Add(dg);
    }
}
else if (e.Node.FirstNode != null && e.Node.FirstNode.Text == "Tables")
{
   dal.changeDatabase(e.Node.Text);

}

关于c# - 为什么在winforms应用程序中点击treeview节点时会出现异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6169395/

相关文章:

C# Gmail 设置启用 POP3

c# - 如何使类受继承保护?

c++ - MFC TreeView 控件 : looking for a foolproof way to deal with data

c# - 当点击树中的新节点时,如何获取旧节点?

c# - protobuf-net:无法序列化类型数据,如何使用 Protocol Buffer 定义类型数据?

c# - 如何在客户端部署带有sql server数据库的应用程序

c# - WinForm 弹出窗体与父级的关系

c# - Canvas 上的 ScaleTransform 调整大小以比 child 更高的速度缩小 Canvas

events - 如何在TreeView kendo ui上获取选定节点的数据?

c# - V 模型测试方法对敏捷开发团队有用吗?