我的 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/