在做C#winform的TreeView并使用XML存储TreeView的信息,将TreeNode.Tag赋为了Dictionary<string, string>,希望能够在TreeView中能存储一些数据,但是现在在使用treeView_MouseUp方法的时候Dictionary<string, string>的对象一直是null。请给解决下,谢谢了
这个是treeView_MouseUp方法
private void treeView1_MouseUp(object sender, MouseEventArgs e)
{
try
{
Point mpt = new Point(e.X, e.Y);
TreeNode TreeClickNode1 = this.treeView1.GetNodeAt(mpt);
//dict = (Dictionary<string, string>)TreeClickNode1.Tag;
// string str= TreeClickNode1.Tag.ToString();
// String str1=str;
if (TreeClickNode1 != null)
{
dict = (Dictionary<string, string>)TreeClickNode1.Tag;
CreatMenu(dict["tag"]);
//CreatMenu(TreeClickNode1.Tag.ToString());
if (e.Button == MouseButtons.Right)
{
this.contextMenuStrip.Show(this.treeView1, mpt); //在mpt位置实现treeview1的点击菜单栏
//this.treeView1.ContextMenu.Show(treeView1,mpt);
}
}
else
{
MessageBox.Show("点击了");
contextMenuStrip.Items.Clear();
}
}
catch
{
}
}
下面是全部代码,AddUnit,AddUser,AddLowest 是添加节点的form类就没有写出
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Collections;
using TreeView;
using System.Net.Sockets;
namespace GlassProcess
{
public partial class DbView : Form
{
static List<string> array1 = new List<string>();
string filepath;
string menufilepath;
string proname;
public string unit;
public string user;
public string lowest;
public string company;
private bool tmpBool;
XmlOperator xmloper;
bool haveUnit = false;
bool haveUser = false;
bool havelowest = false;
Dictionary<string, string> dict = new Dictionary<string, string>();
public DbView( )
{
filepath = Application.StartupPath; //获取应用程序的启动路径
//menufilepath = filepath + "\\Menu.xml"; //菜单文件路径
xmloper = new XmlOperator(filepath, "Menu.xml"); //创建XML操作类
InitializeComponent(); //初始化组件
}
private void DbView_Load(object sender, EventArgs e)
{
LoadFormXml(); //载入数据,生成列表
treeView1.CheckBoxes = false; //关闭复选框
}
//载入数据 生成列表
private void LoadFormXml()
{
XmlNodeList xmlNodes = xmloper.GetXmlNodeList(); //获取XML节点列表
this.treeView1.BeginUpdate(); //更新TreeView
this.treeView1.Nodes.Clear(); //清空TreeView节点
XmlNode2TreeNode(xmlNodes, this.treeView1.Nodes); //节点转换为TreeView节点
this.treeView1.EndUpdate(); //结束更新TreeView
ExpandRoot(this.treeView1.Nodes); //展开TreeView节点
}
//展开节点
private void ExpandRoot(TreeNodeCollection treeNodes)
{
foreach (TreeNode treeNode in treeNodes)
{
if (dict["tag"].Equals("root")) //如果是根节点
{
treeNode.Expand(); //展开节点
}
else if (dict["tag"].Equals("area")) //如果是区域节点
{
treeNode.Collapse(); //折叠节点
}
if (treeNode.Nodes.Count > 0) //如果有子节点
{
ExpandRoot(treeNode.Nodes); //递归展开子节点
}
}
}
private void XmlNode2TreeNode(XmlNodeList xmlNode, TreeNodeCollection treeNode)
{
foreach (XmlNode xmlnode in xmlNode)
{
if (xmlnode.NodeType != XmlNodeType.Element) //忽略非Element类型的节点
{
continue;
}
TreeNode treenode = new TreeNode(); //新建一个TreeNode,并根据XML节点的Title属性设置文本
treenode.Text = xmlnode.Attributes["Title"].Value;
//dict.Add("tag","null");
if (xmlnode.HasChildNodes) //如果XML节点有子节点,则递归调用XmlNode2TreeNode方法转换子节点
{
if (xmlnode.ChildNodes[0].NodeType == XmlNodeType.CDATA) //如果第一个子节点是CDATA,则将其内容作为TreeNode的Tag
{
string str;
str= xmlnode.ChildNodes[0].Value.ToString();
dict["tag"] = str;
if (dict["tag"].Equals("root"))
{
treenode.ImageIndex = 0;
treenode.SelectedImageIndex = 0;
treenode.Expand();
}
else if (dict["tag"].Equals("area"))
{
treenode.ImageIndex = 1;
treenode.SelectedImageIndex = 1;
}
else if (dict["tag"].Equals("user"))
{
treenode.ImageIndex = 2;
treenode.SelectedImageIndex = 2;
}
else
{
treenode.ImageIndex = 2;
treenode.SelectedImageIndex = 2;
}
}
//将新建的TreeNode添加到父TreeNode的Nodes 集合中
XmlNode2TreeNode(xmlnode.ChildNodes, treenode.Nodes);
}
//将新建的TreeNode添加到TreeView的节点集合中
treeNode.Add(treenode);
}
}
private void treeView1_MouseUp(object sender, MouseEventArgs e)
{
try
{
Point mpt = new Point(e.X, e.Y);
TreeNode TreeClickNode1 = this.treeView1.GetNodeAt(mpt);
//dict = (Dictionary<string, string>)TreeClickNode1.Tag;
// string str= TreeClickNode1.Tag.ToString();
// String str1=str;
if (TreeClickNode1 != null)
{
dict = (Dictionary<string, string>)TreeClickNode1.Tag;
CreatMenu(dict["tag"]);
//CreatMenu(TreeClickNode1.Tag.ToString());
if (e.Button == MouseButtons.Right)
{
this.contextMenuStrip.Show(this.treeView1, mpt); //在mpt位置实现treeview1的点击菜单栏
//this.treeView1.ContextMenu.Show(treeView1,mpt);
}
}
else
{
MessageBox.Show("点击了");
contextMenuStrip.Items.Clear();
}
}
catch
{
}
}
private void CreatMenu(string p)
{
switch (p)
{
case "root":
{
//清空右键菜单
this.contextMenuStrip.Items.Clear();
//创建“新增用户分区”菜单项,并添加到右键菜单
ToolStripMenuItem AddArea = new ToolStripMenuItem();
AddArea.Name = "新增用户分区";
AddArea.Text = "新增用户分区";
AddArea.Click += new System.EventHandler(AddArea_Click);
contextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {AddArea});
/*
上面这段代码用于在 ContextMenuStrip 控件中添加一个 ToolStripMenuItem 控件,其中 AddArea 是 ToolStripMenuItem 控件的实例。具体解释如下:
- contextMenuStrip:ContextMenuStrip 控件的实例,用于显示右键菜单。
- Items:ContextMenuStrip 类的属性,表示右键菜单中包含的所有 ToolStripItem 对象的集合。
- AddRange:ToolStripItemCollection 类的方法,用于向 ToolStripItem 对象的集合中添加 ToolStripItem 数组的元素。
- new System.Windows.Forms.ToolStripItem[]:表示创建一个 ToolStripItem 数组的实例。
- {AddArea}:表示添加 ToolStripMenuItem 实例 AddArea 到 ToolStripItem 数组中。
因此,这段代码的作用是将一个名为 AddArea 的 ToolStripMenuItem 添加到 ContextMenuStrip 控件中显示在右键菜单中。
*/
}
break;
case "area":
{
//清空右键菜单
this.contextMenuStrip.Items.Clear();
//创建“添加用户”菜单项,并添加到右键菜单
ToolStripMenuItem AddUser = new ToolStripMenuItem();
AddUser.Name = "添加用户";
AddUser.Text = "添加用户";
AddUser.Image = this.treeImgs.Images[3];
AddUser.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
AddUser.Click += new System.EventHandler(AddUser_Click);
//创建“删除组”菜单项,并添加到右键菜单
ToolStripMenuItem DeleteArea = new ToolStripMenuItem();
DeleteArea.Name = "删除组";
DeleteArea.Text = "删除组";
DeleteArea.Click += new System.EventHandler(DeleteArea_Click);
contextMenuStrip.Items.AddRange(
new System.Windows.Forms.ToolStripItem[] {
AddUser,DeleteArea
}
);
}
break;
case "user":
{
//清空右键菜单
this.contextMenuStrip.Items.Clear();
//创建“删除用户菜单项”,并添加到右键菜单
ToolStripMenuItem DeleteUser = new ToolStripMenuItem();
DeleteUser.Name = "删除用户";
DeleteUser.Text = "删除用户";
DeleteUser.Click += new System.EventHandler(DeleteUser_Click);
ToolStripMenuItem Property = new ToolStripMenuItem();
Property.Name = "添加元件";
Property.Text = "添加元件";
Property.Click += new System.EventHandler(AddLowest_Click);
contextMenuStrip.Items.AddRange(
new System.Windows.Forms.ToolStripItem[] {DeleteUser,Property});
}
break;
case "lowest":
{
//清空右键菜单
this.contextMenuStrip.Items.Clear();
//创建“删除用户菜单项”,并添加到右键菜单
ToolStripMenuItem DeleteUser = new ToolStripMenuItem();
DeleteUser.Name = "删除元件";
DeleteUser.Text = "删除元件";
DeleteUser.Click += new System.EventHandler(DeleteLowest_Click);
contextMenuStrip.Items.AddRange(
new System.Windows.Forms.ToolStripItem[] { DeleteUser });
}
break;
}
}
//private void ContractListBakRootItem_Click(object sender, EventArgs e)
//{
// //this.treeView1.ExpandAll();
//}
private void ContractListBakGroupItem_Click(object sender, EventArgs e)
{
List<string> array = new List<string>();
foreach (TreeNode node in this.treeView1.SelectedNode.Nodes)
{
array.Add((node.Text.Split('/'))[0]);
}
//this.treeView1.ExpandAll();
}
//private void ImportDataUser_Click(object sender, EventArgs e)
//{
// //this.treeView1.ExpandAll();
//}
private void SearchTreeNode(TreeNodeCollection treeNodes,string fileName)
{
//在指定的节点集合treeNodes中搜索名为fileName的节点并删除
foreach (TreeNode treeNode in treeNodes)
{
dict = (Dictionary<string, string>)treeNode.Tag;
if (dict["tag"] == "user")
{
if (treeNode.Text.Equals(fileName))
{
this.treeView1.Nodes.Remove(treeNode);
}
continue;
}
if (treeNode.Nodes.Count > 0)
{
SearchTreeNode(treeNode.Nodes, fileName);
}
}
}
private TreeNode CreateChildNodeByImport(string file)
{
//根据导入的文件名创建一个新的树节点并返回
TreeNode node = new TreeNode(file);
dict = (Dictionary<string, string>)node.Tag;
dict["tag"]= "user";
return node;
}
//递归查找并删除TreeView控件中指定用户的节点
private void RemoveUser(TreeNodeCollection treeNodes)
{
foreach (TreeNode treeNode in treeNodes)
{
dict = (Dictionary<string, string>)treeNode.Tag;
if (dict["tag"].Equals("user"))
{
if (treeNode.Text.Equals(user))
{
treeNode.Remove();
}
}
else if (dict["tag"].Equals("lowest"))
{
if (treeNode.Text.Equals(lowest))
{
treeNode.Remove();
}
}
if (treeNode.Nodes.Count > 0) //treeNode.Nodes.Count表示该节点下子节点个数
{
RemoveUser(treeNode.Nodes);
}
}
}
private void AddArea_Click2(object sender, EventArgs e) //添加区域
{
AddUnit form = new AddUnit(this);
form.ShowDialog();
if (!string.IsNullOrEmpty(unit))
{
TreeNode node = CreateRootNode();
//this.treeView1.Nodes.
//TreeNode root = this.treeView1.Nodes[0];
this.treeView1.Nodes[0].Nodes.Add(node);
SaveToXml();
LoadFormXml();
}
//this.treeView1.ExpandAll();
}
private void AddArea_Click(object sender, EventArgs e)
{
//创建AddUser窗体的实例
AddUnit form = new AddUnit(this);
//显示窗体,等待用户输入
// if (form.ShowDialog()== DialogResult.OK)
form.ShowDialog();
if (!string.IsNullOrEmpty(unit))
{
//检查Tree View控件中是否已经存在指定用户的节点
Check(this.treeView1.Nodes);
if (haveUnit)
{
//如果用户已经存在,弹出确认对话框
MessageBox.Show("该组[" + unit + "]已经存在");
}
else
{ //如果用户不存在,创建新的节点
TreeNode node = CreateRootNode();
//TreeNode selectNode = this.treeView1.SelectedNode;
//selectNode.Nodes.Add(node); //adduser
this.treeView1.Nodes[0].Nodes.Add(node);
SaveToXml(); //重新从XML文件中加载数据并更新Tree View控件
LoadFormXml();
}
}
// }
haveUnit = false; //重置haveUnit
}
//添加元件
private void AddLowest_Click(object sender, EventArgs e)
{
//创建AddUser窗体的实例
AddLowest form = new AddLowest(this);
//显示窗体,等待用户输入
if (form.ShowDialog() == DialogResult.OK)
{
if (!string.IsNullOrEmpty(lowest))
{
//检查Tree View控件中是否已经存在指定用户的节点
Check(this.treeView1.Nodes);
if (havelowest)
{
//如果用户已经存在,弹出确认对话框
if (MessageBox.Show("该元件[" + lowest + "]已经存在,是否覆盖?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
//删除原来的节点并创建新的节点
RemoveUser(this.treeView1.Nodes);
TreeNode node = CreateLowestNode();
TreeNode selectNode = this.treeView1.SelectedNode;
selectNode.Nodes.Add(node);
SaveToXml(); //将更改保存到XML文件中
LoadFormXml(); //重新从XML文件中加载数据并更新TreeView控件
}
else
{
//SetNodeBackColor(this.treeView1.Nodes);
return;
}
}
else
{ //如果用户不存在,创建新的节点
TreeNode node = CreateLowestNode();
TreeNode selectNode = this.treeView1.SelectedNode;
selectNode.Nodes.Add(node); //adduser
SaveToXml(); //重新从XML文件中加载数据并更新Tree View控件
LoadFormXml();
}
}
}
haveUser = false; //重置haveUser
}
private void AddUser_Click(object sender, EventArgs e)
{
//创建AddUser窗体的实例
AddUser form = new AddUser(this);
//显示窗体,等待用户输入
if (form.ShowDialog() == DialogResult.OK)
{
if (!string.IsNullOrEmpty(user))
{
//检查Tree View控件中是否已经存在指定用户的节点
Check(this.treeView1.Nodes);
if (haveUser)
{
//如果用户已经存在,弹出确认对话框
MessageBox.Show("该用户[" + user + "]已经存在");
}
else
{ //如果用户不存在,创建新的节点
TreeNode node = CreateChildNode();
TreeNode selectNode = this.treeView1.SelectedNode;
selectNode.Nodes.Add(node);
SaveToXml(); //重新从XML文件中加载数据并更新Tree View控件
LoadFormXml();
}
}
}
haveUser = false; //重置haveUser
}
private void Check(TreeNodeCollection treeNodes) //检查Tree View控件中是否已经存在指定用户的节点
{
tmpBool = false;
foreach (TreeNode treeNode in treeNodes)
{
dict = (Dictionary<string,string>)treeNode.Tag;
if (dict["tag"].Equals("area"))
{
if (treeNode.Text.Equals(unit))
{
treeNode.BackColor = Color.Red; //将节点的背景颜色设为红色
//treeNode
//treeNode.Parent.Expand(); //展开父节点
haveUnit = true; //设置haveUnit为true,表示找到了该用户
}
}
else if (dict["tag"].Equals("user"))
{
if (treeNode.Text.Equals(user))
{
treeNode.BackColor = Color.Red; //将节点的背景颜色设为红色
//treeNode
treeNode.Parent.Expand(); //展开父节点
haveUser = true; //设置haveUser为true,表示找到了该用户
}
}
else if (dict["tag"].Equals("lowest"))
{
if (treeNode.Text.Equals(lowest))
{
treeNode.BackColor = Color.Red; //将节点的背景颜色设为红色
//treeNode
treeNode.Parent.Expand(); //展开父节点
havelowest = true; //设置haveUser为true,表示找到了该用户
}
}
if (treeNode.Nodes.Count > 0)
{
Check(treeNode.Nodes); //递归调用CheckUser,查找子节点中是否存在该用户
}
}
}
private void DeleteLowest_Click(object sender, EventArgs e)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
if (MessageBox.Show("你确定要删除吗?", "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
if (this.treeView1.SelectedNode == null)
{
return;
}
dict = (Dictionary<string, string>)this.treeView1.SelectedNode.Tag;
if (dict["tag"] == "lowest")
{
this.treeView1.Nodes.Remove(this.treeView1.SelectedNode);//移除选中节点
SaveToXml(); //保存到XML文件
LoadFormXml(); //从XML文件加载节点
}
}
}
private void DeleteUser_Click(object sender, EventArgs e)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
if (MessageBox.Show("你确定要删除吗?", "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
if (this.treeView1.SelectedNode == null)
{
return;
}
dict = (Dictionary<string, string>)this.treeView1.SelectedNode.Tag;
if (dict["tag"] == "user")
{
List<string> array = new List<string>();
foreach (TreeNode node in this.treeView1.SelectedNode.Nodes)
{
array.Add(node.Text);
}
if (array.Count != 0)
{
MessageBox.Show("不能删除非空用户的结点!", "确定", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
this.treeView1.Nodes.Remove(this.treeView1.SelectedNode);//移除选中节点
SaveToXml(); //保存到XML文件
LoadFormXml(); //从XML文件加载节点
}
}
}
}
private void DeleteArea_Click(object sender, EventArgs e)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
if (MessageBox.Show("你确定要删除吗?", "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
{
if (this.treeView1.SelectedNode == null)
{
return;
}
dict = (Dictionary<string, string>)this.treeView1.SelectedNode.Tag;
if(dict["tag"] == "area")
{
List<string> array = new List<string>();
foreach (TreeNode node in this.treeView1.SelectedNode.Nodes)
{
//array.Add((node.Text.Split('/'))[0]); //将子节点的文本按照‘/’分割成字符串数组,并取第一个元素,即用户名
array.Add(node.Text); //当前并没有字符串含'/'
}
if (array.Count != 0)
{
MessageBox.Show("不能删除非空用户的组结点!", "确定", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
this.treeView1.Nodes.Remove(this.treeView1.SelectedNode);//移除选中节点
SaveToXml(); //保存到XML文件
LoadFormXml(); //从XML文件加载节点
//binary.DeleteAccountDirectory(array[0]);
}
}
}
}
// 点击列表项
//private void ListItem_Click(object sender, EventArgs e)
//{
// TODO: 实现点击列表项后的操作
//}
// 添加选项卡页
//private void AddTabPage(string pageTitle, Control ctrForm)
//{
// TODO: 实现添加选项卡页的操作
//}
// 双击树形视图
private void treeView1_DoubleClick(object sender, EventArgs e)
{
// MessageBox.Show("双击了"); // TODO: 实现双击树形视图后的操作
}
// 添加单元工具按钮的点击事件
private void toolbtn_AddUnit_Click(object sender, EventArgs e)
{
// 打开添加单元的窗口
AddUnit form = new AddUnit(this);
form.ShowDialog();
if (!string.IsNullOrEmpty(unit))
{
// 创建根节点
TreeNode node = CreateRootNode();
// 添加节点到树形视图中
this.treeView1.Nodes[0].Nodes.Add(node);
SaveToXml(); // 将树形视图保存到XML文件中
LoadFormXml(); // 从XML文件中加载树形视图
}
//this.treeView1.ExpandAll();
}
// 创建根节点
private TreeNode CreateRootNode()
{
Dictionary<String, String> dict = new Dictionary<String, String>();
dict.Add("tag", "area");
TreeNode node = new TreeNode(this.unit);
node.Tag = dict;
node.ImageIndex = 1;
node.SelectedImageIndex = 1;
return node;
}
// 创建子节点
private TreeNode CreateChildNode()
{
Dictionary<String, String> dict = new Dictionary<String, String>();
dict.Add("tag", "user");
TreeNode node = new TreeNode(this.user);
node.Tag = dict;
node.ImageIndex = 2;
node.SelectedImageIndex = 2;
return node;
}
private TreeNode CreateLowestNode()
{
Dictionary<String, String> dict = new Dictionary<String, String>();
dict.Add("tag", "lowest");
TreeNode node = new TreeNode(this.lowest);
node.Tag = dict;
return node;
}
//private TreeNode Create1Node()
//{
// Dictionary<String,String> dict =new Dictionary<String,String>();
// dict.Add("tag","lowest");
// TreeNode node = new TreeNode(this.lowest);
// node.Tag = dict["tag"];
// //node.ImageIndex = 2;
// //node.SelectedImageIndex = 2;
// return node;
//}
// 将树形视图保存到XML文件中
public void SaveToXml()
{
// 创建XML文档对象
XmlDocument doc = new XmlDocument();
// 创建根节点
doc.LoadXml("<Menu></Menu>");
XmlNode root = doc.DocumentElement;
// 添加XML声明
doc.InsertBefore(doc.CreateXmlDeclaration("1.0", "utf-8", "yes"), root);
// 将树形视图转换为XML节点,并添加到XML文档中
TreeNode2Xml(this.treeView1.Nodes, root);
// 将XML文档保存到文件中
xmloper.SaveXml(doc);
}
// 将TreeNodeCollection转换为XML节点
private void TreeNode2Xml(TreeNodeCollection treeNodes, XmlNode xmlNode)
{
XmlDocument doc = xmlNode.OwnerDocument;
foreach (TreeNode treeNode in treeNodes)
{
dict = (Dictionary<string, string>)treeNode.Tag;
// 创建XML节点
XmlNode element = doc.CreateNode("element", "Item", ""); //创建名为item的xml对象
XmlAttribute attr = doc.CreateAttribute("Title");
attr.Value = treeNode.Text; //属性值为treeNode.Text
element.Attributes.Append(attr); //添加名为Title的属性
element.AppendChild(doc.CreateCDataSection(dict["tag"])); //将treeNode转换为CDataSection并将其作为子节点添加到element中
xmlNode.AppendChild(element); //将element添加到xmlNode子节点中
// 如果该节点有子节点,则递归调用该方法
if (treeNode.Nodes.Count > 0)
{
TreeNode2Xml(treeNode.Nodes, element);
}
}
}
// 当用户选中某个节点时发生的事件处理程序
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
string path = null;
TreeNode node = this.treeView1.SelectedNode;
//node.ForeColor = Color.Red;
if (node != null)
{
path = node.Text;
while (node.Parent != null)
{
node = node.Parent;
path = node.Text + "\\" + path;
}
}
}
// 当用户单击树形视图时发生的事件处理程序
private void treeView1_Click(object sender, EventArgs e)
{
// 获取鼠标单击的位置上的节点
object tmpObj = this.treeView1.GetNodeAt(this.treeView1.PointToClient(Cursor.Position));
if (tmpObj != null)
{
if ((tmpObj as TreeNode).Bounds.Contains(this.treeView1.PointToClient(Cursor.Position)))
{
tmpBool = true;
}
}
}
// 当用户展开某个节点之前发生的事件处理程序
private void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
if (tmpBool)
{
e.Cancel = tmpBool;
}
tmpBool = false;
}
// 当用户折叠某个节点之前发生的事件处理程序
private void treeView1_BeforeCollapse(object sender, TreeViewCancelEventArgs e)
{
if (tmpBool)
{
e.Cancel = tmpBool;
}
tmpBool = false;
}
// 当用户在树形视图上单击鼠标按钮时发生的事件处理程序
private void treeView1_MouseClick(object sender, MouseEventArgs e){}
// 当用户在树形视图上移动鼠标时发生的事件处理程序
private void treeView1_MouseMove(object sender, MouseEventArgs e)
{
}
// 当鼠标离开树形视图时发生的事件处理程序
private void treeView1_MouseLeave(object sender, EventArgs e)
{
}
private void toolbtnSearch_Click(object sender, EventArgs e)
{
string searchName = this.toolText.Text;
SetNodeBackColor(this.treeView1.Nodes);
if (!string.IsNullOrEmpty(searchName))
{
SearchXml(this.treeView1.Nodes, searchName); // 根据搜索内容在TreeView中查找匹配节点
}
}
private void SetNodeBackColor(TreeNodeCollection treeNodes)
{
foreach (TreeNode treeNode in treeNodes)
{
dict = (Dictionary<string, string>)treeNode.Tag;
treeNode.BackColor = Color.White; // 设置节点背景颜色为白色
if (dict["tag"].Equals("area")) // 如果节点的Tag属性值为"area",则将该节点折叠
{
treeNode.Collapse();
}
if (treeNode.Nodes.Count > 0)
{
SetNodeBackColor(treeNode.Nodes); // 递归调用SetNodeBackColor方法,对当前节点的所有子节点执行相同的操作
}
}
}
private void SearchXml(TreeNodeCollection treeNodes,string search)
{
foreach (TreeNode treeNode in treeNodes)
{
if (treeNode.Text.ToString().Contains(search)) // 如果当前节点的文本内容包含搜索内容,则将该节点的背景颜色设置为Coral色
{
treeNode.BackColor = Color.Coral;
if(treeNode.Parent!=null) // 如果该节点有父节点,则展开其父节点
{
treeNode.Parent.Expand();
}
}
if (treeNode.Nodes.Count > 0)
{
SearchXml(treeNode.Nodes,search); // 递归调用SearchXml方法,对当前节点的所有子节点执行相同的操作
}
}
}
private void toolText_TextChanged(object sender, EventArgs e)
{
toolbtnSearch_Click(sender, e); // 当搜索框文本内容发生变化时,执行toolbtnSearch_Click方法
}
//节点的选中取消事件
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
if (e.Node.Checked) // 如果当前节点被选中,则将其所有子节点的选中状态设置为true
{
setChildNodeCheckedState(e.Node, true);
}
else // 如果当前节点未选中,则将其所有子节点的选中状态设置为false
{
setChildNodeCheckedState(e.Node, false);
}
}
//选中节点之后,选中节点的所有子节点
private void setChildNodeCheckedState(TreeNode currNode, bool state)
{
TreeNodeCollection nodes = currNode.Nodes;
if (nodes.Count > 0)
foreach (TreeNode tn in nodes)
{
tn.Checked = state; // 将当前子节点的选中状态设置为指定的状态
setChildNodeCheckedState(tn, state); // 递归调用setChildNodeCheckedState方法,对当前子节点的所有子节点执行相同的操作
}
}
}
}