Visual Studio .NET 2003.NET 1.1Visual Studio 2005.NET 2.0Windows Forms中级开发Visual StudioWindows.NETC#
C# TreeView 遍历






2.75/5 (23投票s)
2006 年 3 月 20 日

75951

1652
本文介绍了一种简单的 C# TreeView 遍历机制。
引言
C# 中的 TreeView 是一个很棒的控件。TreeView 可用于构建分层菜单。我参与了一个项目,在该项目中我需要大量使用 TreeView,因此我编写了一些代码来动态构建 TreeView(数据库驱动)。在这里,我展示 TreeView 遍历操作。
这是填充后的 TreeView 的快照。
这是代码
class TVIEW
//1- Create a TreeView
TreeView treeview = new TreeView();
//2- Populate the TreeView with Data
//populateTreeView();
//3- Now You can visit each and every node of this treeview whenever you require
TVIEW t1 = new TVIEW();
t1.TraverseTreeView(treeview);
private void TraverseTreeView(TreeView tview)
{
//Create a TreeNode to hold the Parent Node
TreeNode temp = new TreeNode();
//Loop through the Parent Nodes
for(int k=0; k<tview.Nodes.Count; k++)
{
//Store the Parent Node in temp
temp = tview.Nodes[k];
//Display the Text of the Parent Node i.e. temp
MessageBox.Show(temp.Text);
//Now Loop through each of the child nodes in this parent node i.e.temp
for (int i = 0; i < temp.Nodes.Count; i++)
visitChildNodes(temp.Nodes[i]); //send every child to the function for further traversal
}
私有的 voidvisitChildNodes(TreeNode node)
{
//Display the Text of the nodeMessageBox.Show(node.Text);
//Loop Through this node and its childs recursively
for (int j = 0; j < node.Nodes.Count; j++)
visitChildNodes(node.Nodes[j]);
}