如何通过在TreeView中单击它来打开文件

时间:2018-01-14 18:49:09

标签: winforms treeview

单击树中最低的子节点时,如何打开文件(例如PDF)。

我创建了一个TreeView程序,该程序由数据库文件自动填充。 example

2 个答案:

答案 0 :(得分:0)

您需要查看TreeNode Class

示例:

private void Form1_Load(object sender, EventArgs e)
    {
        //
        // This is the first node in the view.
        //
        TreeNode treeNode = new TreeNode("Windows");
        treeView1.Nodes.Add(treeNode);
        //
        // Another node following the first node.
        //
        treeNode = new TreeNode("Linux");
        treeView1.Nodes.Add(treeNode);
        //
        // Create two child nodes and put them in an array.
        // ... Add the third node, and specify these as its children.
        //
        TreeNode node2 = new TreeNode("C#");
        TreeNode node3 = new TreeNode("VB.NET");
        TreeNode[] array = new TreeNode[] { node2, node3 };
        //
        // Final node.
        //
        treeNode = new TreeNode("Dot Net Perls", array);
        treeView1.Nodes.Add(treeNode);
    }

虽然示例不是从DB读取节点。你可以这样写一个查询来获取节点。遵循以下路径的步骤,它将引导你从头开始

Create a TreeView from a Database in Windows Forms and C#

示例来源:Tree View

要在节点上打开文件,请单击

  

public event TreeNodeMouseClickEventHandler NodeMouseClick

    // If a node is double-clicked, open the file indicated by the TreeNode.
    void treeView1_NodeMouseClick(object sender, 
            TreeNodeMouseClickEventArgs e)
    {
    try
    {
        System.Diagnostics.Process.Start(@"c:\" + e.Node.Text);//e.Node.Text contains fileName
    }
        // If the file is not found, handle the exception and inform the user.
    catch (System.ComponentModel.Win32Exception)
    {
        MessageBox.Show("File not found.");
    }

答案 1 :(得分:0)

将路径关联到该节点,然后使用以下内容:

private void LinkClicked(object sender, LinkClickedEventArgs e)
{
    Process.Start(@".\" + "YOUR FILE NAME AND EXTENSION");
}

阅读:Process.Start

  

通过指定文档或应用程序的名称来启动流程资源   文件并将资源与新的System.Diagnostics.Process组件关联。