如何在选定的树视图节点上打开文件 [英] How to open files on selected treeview node
问题描述
我有一个treeView控件,里面装有来自C盘的文件夹和文件,我希望用户选择节点并打开所选文件。
我如何打开所选节点上的文件?
我尝试了什么:
我试过以下代码它不起作用
String TreenodeName = treeView1.SelectedNode.ToString()。Replace(TreeNode:,String.Empty);
MessageBox.Show(Path +\\ + TreenodeName);
System.Diagnostics.Process.Start(Path +\\+ TreenodeName);
I have a treeView control filled with folders and files in from C drive and I want users to select node and open the selected file.
How do i open files on selected node?
What I have tried:
I have tried the following code it doesnt work
String TreenodeName = treeView1.SelectedNode.ToString().Replace("TreeNode:", String.Empty);
MessageBox.Show(Path + "\\" + TreenodeName);
System.Diagnostics.Process.Start(Path + "\\" + TreenodeName);
推荐答案
取决于一些事情,但对于初学者,不要这样做。
首先检查节点:
Depends on a couple of things, but for starters, don't do it like that.
Start by checking the node:
TreeNode node = treeView1.SelectedNode;
if (node != null)
{
...
这样,如果用户没有选择节点,则代码不会失败。根据您为此代码处理的事件,您可以在没有选择时获取事件。
然后,不要使用ToString和Replace,而是使用Text属性:
That way, if the user hasn't selected a node, your code doesn't fail. And depending on the event you are handling for this code, you can get an event when there is no selection.
Then, don't use ToString and Replace, use the Text property instead:
TreeNode node = treeView1.SelectedNode;
if (node != null)
{
string treeNodeName = node.Text;
...
它更加明显,而且效率更高。
之后,如果您的Path是一个字符串,它是实际的路径文件夹或文件,它应该工作。但是......我会使用TreeNode.Tag属性来保存文件/文件夹的完整路径,而不是在需要它时构建它,因为它可以节省你在哪里工作的麻烦!
即使你自己构建它,最好使用Path.Combine方法而不是手动连接字符串。
It's a lot more obvious, as well as more efficient.
After that, provided your Path is a string which is the actual path to the folder or file, it should work. But...I'd use the TreeNode.Tag property to hold the full path to the file / folder instead of building it when I needed it as it saves the hassle of working out where you are!
Even if you do build it yourself, it's a good idea to use the Path.Combine method instead of manually concatenating the strings.
这篇关于如何在选定的树视图节点上打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!