从填充了.rtf文件的TreeView中打开RichTextBox中的.rtf文件

时间:2015-09-08 17:29:42

标签: c# visual-studio treeview

我有一个填充了.rtf文件的TreeView,我想在点击treenode时将文件加载到RichTextBox中。

以下是代码:

private string currentLocation = Directory.GetCurrentDirectory() + "\\Notes";
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
    string loc = currentLocation + "\\" + treeView1.SelectedNode.Text+ ".rtf";
    FileStream fs = new FileStream(loc, FileMode.Open, FileAccess.Read);
    richTextBox1.LoadFile(fs, RichTextBoxStreamType.RichText);
}

以下是点击treenode后发生的错误:

  

未处理的类型' System.NullReferenceException'发生在WindowsFormsApplication1.exe

中      

附加信息:未将对象引用设置为对象的实例。

1 个答案:

答案 0 :(得分:0)

使用

private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
    TreeNode tn=e.Node;
    string loc = currentLocation + "\\" + tn.Text+ ".rtf";
    richTextBox1.LoadFile(loc);
}

首先将所选的(你无法从树视图中获取所选节点)节点转换为TreeNode,然后使用命令tn.Text获取所选节点的文本(文件名),之后你说到富文本框从路径加载文件(您不需要分配文件流)。