【发布时间】:2009-03-03 12:46:17
【问题描述】:
有点傻的问题,但是卡了很长时间。
我编写了两个类,一个是 Form(TreeDisplay 类),另一个包含业务逻辑(MyTreeNode 类)。
TreeDisplay 类包含用于选择文件的浏览按钮,并将其传递给 MyTreeNode 类中的方法 initiatingTree(string filename)。
现在我必须将此字符串参数文件名传递给 MyTreeNode 类。当我运行我的代码时,我选择的 XML 文件显示在文本框中,但不在树视图中。
我已经编写了部分代码,但它正在抛出 NullReferenceException(对象引用未设置为对象的实例)。
当整个代码编写在 Form.cs 中时,代码运行成功,但在分离业务逻辑时发生了异常。
你能告诉我我哪里错了吗?
这是TreeDisplay类(我的主窗体)的浏览按钮中的代码:
if (open.ShowDialog(this) == DialogResult.OK)
{
txtFileName.Text = open.FileName;
MytreeNodeClass treenodeClass = new MytreeNodeClass();
treenodeClass.initiatingTree(open.FileName,treeView1);
}
这是我的 MyTreeNode 类中的 initiatingTree() 代码:
public class MytreeNodeClass
{
private readonly System.Windows.Forms.TextBox txtFileName;
private TreeView treeView1;
private readonly ToolStripStatusLabel toolStripStatusLabel1;
public string Filename
{
get { return filename; }
}
protected string filename;
public MytreeNodeClass()
{
}
public void initiatingTree(string nameofFile,TreeView treeView1)
{
try
{
//Create XML document & load the XML file.
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(nameofFile);
treeView1 = new System.Windows.Forms.TreeView();
treeView1.Nodes.Clear();
if (xmlDocument.DocumentElement != null)
{
TreeNode treeNodedoc = new TreeNode(xmlDocument.DocumentElement.Name);
treeView1.Nodes.Add(treeNodedoc);
}
在使用断点 treeView1.Nodes.Clear() 时,代码从这一行出来并进入抛出 NullReferenceException 的 catch 块。
请帮助找出异常的根本原因。谢谢。
【问题讨论】: