遍历TreeView
有两种遍历方式:
一:使用递归遍历
//my_condition条件
public void FindNodeFunc(string my_condition)
{
TreeView1.Focus();
foreach(TreeNode item in TreeView1.Nodes)
{
DiGuiFunc(item, my_condition);
}
}
public void DiGuiFunc(TreeNode tn, string my_condition)
{
foreach(TreeNode tnSub in tn.Nodes)
{
//此时比较的数据是存放在节点的Name属性中
if(tnSub.Name.ToString() == my_condition)
{
Console.WriteLine("找到了"); //找到了节点
//将节点置为选中状态
DeviceEventTree.SelectedNode = tnSub;
//直接返回
return;
}
DiGuiFunc(tnSub, my_condition);
}
}
二:根据层级直接遍历
//此时只有两级节点,多级方法类似。
for (int i = 0; i < DeviceEventTree.Nodes.Count; i++)
{
for (int j = 0; j < DeviceEventTree.Nodes[i].Nodes.Count; j++)
{
if (DeviceEventTree.Nodes[i].Nodes[j].Name.ToString() == my_condition)
{
DeviceEventTree.SelectedNode = DeviceEventTree.Nodes[i].Nodes[j];
DeviceEventTree.Nodes[i].Expand();//展开父级
return;
}
}
}
推荐使用第一种方式,遍历起来更加方便。