treeView1.SelectedNode = treeView1.Nodes[0]; //选中当前treeview控件的根节点为当前节点添加子节点:
TreeNode tmp;
tmp = new TreeNode("需要添加的内容");
treeView1.SelectedNode.Nodes.Add(tmp);
treeView1.SelectedNode = tmp;
为父节点添加子节点:
TreeNode tmp;
tmp = new TreeNode("需添加的内容");
treeView1.SelectedNode.Parent.Nodes.Add(tmp);
treeView1.SelectedNode = tmp;
设置当鼠标移开treeView控件时选中状态不消失
treeView1.HideSelection = false;
显示某一目录下的文件
private void PaintTreeView(TreeView treeView, string fullPath)
{
try
{
treeView.Nodes.Clear(); //清空TreeView
DirectoryInfo dirs = new DirectoryInfo(fullPath); //获得程序所在路径的目录
DirectoryInfo[] dir = dirs.GetDirectories(); //获取目录下文件夹选项
FileInfo[] file = dirs.GetFiles(); //获取目录下文件选项
int dircount = dir.Count(); //获取文件夹对象数量
int filecount = file.Count(); //获取文件对象数量
for (int i = 0; i < dircount; i++) //循环文件夹
{
treeView.Nodes.Add(dir[i].Name);
string pathNode = fullPath + "\\" + dir[i].Name;
GetMultiNode(treeView.Nodes[i], pathNode);
}
for (int j = 0; j < filecount; j++)
{
treeView.Nodes.Add(file[j].Name);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private bool GetMultiNode(TreeNode treeNode, string path)
{
if (Directory.Exists(path) == false)
{
return false;
}
DirectoryInfo dirs = new DirectoryInfo(path); //获得程序所在路径的目录对象
DirectoryInfo[] dir = dirs.GetDirectories(); //获得目录下文件夹对象
FileInfo[] file = dirs.GetFiles(); //获得目录下文件对象
int dircount = dir.Count(); //获取文件夹对象数量
int filecount = file.Count(); //获取文件对象数量
int sumcount = dircount + filecount;
if (sumcount == 0)
{
return false;
}
for (int j = 0; j < dircount; j++) //循环文件夹
{
treeNode.Nodes.Add(dir[j].Name);
string pathNodeB = path + "\\" + dir[j].Name;
GetMultiNode(treeNode.Nodes[j], pathNodeB);
}
for (int j = 0; j < filecount; j++) //循环文件
{
treeNode.Nodes.Add(file[j].Name);
}
return true;
}
判断不同层次的节点,显示不同的右键内容:
private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
TreeNode temp = treeView1.GetNodeAt(e.X, e.Y); //获取当前鼠标点击的位置
treeView1.LabelEdit = false; //设置当前不可编辑
if (temp != null)
{
treeView1.SelectedNode = temp;
temp.ToolTipText = "右键可编辑"; //鼠标放在节点位置,提示右键可编辑
if (temp.Level == 0)
{
treeView1.ContextMenuStrip = 模板分类管理;
//绑定不同的右键选项,ContextMenuStrip名字模板分类管理
}
else
treeView1.ContextMenuStrip = 模板管理;
}
else
{
treeView1.SelectedNode = null;
treeView1.ContextMenuStrip = null;
return;
}
}