gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:38:17 24 4
gpt4 key购买 nike

我对 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);

}
}

p.s 对不起英语不好

最佳答案

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

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

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com