TreeView搜索

此函数仅查找树视图中的第一个节点,其中包含SearchText。

private TreeNode SearchNode(string SearchText,TreeNode StartNode) { TreeNode node=null; while (StartNode!= null) { if (StartNode.Text.ToLower().Contains(SearchText.ToLower())) { node = StartNode; break; }; if (StartNode.Nodes.Count != 0) { node=SearchNode(SearchText, StartNode.Nodes[0]);//Recursive Search if (node != null) { break; }; }; StartNode = StartNode.NextNode; }; return node; } private void button1_Click(object sender, EventArgs e) { string SearchText = this.textBox1.Text; if (SearchText == "") { return; }; TreeNode SelectedNode = SearchNode(SearchText, treeView1.Nodes[0]); if (SelectedNode != null) { this.treeView1.SelectedNode = SelectedNode; this.treeView1.SelectedNode.Expand(); this.treeView1.Select(); }; } 

我应该如何更改它,因此该函数不仅能够找到第一个节点,而且还能找到所有这些节点,每次单击button1时,它都会找到下一个节点直到结束,然后从头开始。 所以我不应该从TreeView1.Nodes [0]搜索,而是从TreeView1.SelectedNode搜索…

如下所示应该可以添加到您的表单代码中。

  private List CurrentNodeMatches = new List(); private int LastNodeIndex = 0; private string LastSearchText; private void button1_Click(object sender, EventArgs e) { string searchText = this.textBox1.Text; if (String.IsNullOrEmpty(searchText)) { return; }; if (LastSearchText != searchText) { //It's a new Search CurrentNodeMatches.Clear(); LastSearchText = searchText; LastNodeIndex = 0; SearchNodes(searchText, treeView1.Nodes[0]); } if (LastNodeIndex >= 0 && CurrentNodeMatches.Count > 0 && LastNodeIndex < CurrentNodeMatches.Count) { TreeNode selectedNode = CurrentNodeMatches[LastNodeIndex]; LastNodeIndex++; this.treeView1.SelectedNode = selectedNode; this.treeView1.SelectedNode.Expand(); this.treeView1.Select(); } } private void SearchNodes(string SearchText, TreeNode StartNode) { TreeNode node = null; while (StartNode != null) { if (StartNode.Text.ToLower().Contains(SearchText.ToLower())) { CurrentNodeMatches.Add(StartNode); }; if (StartNode.Nodes.Count != 0) { SearchNodes(SearchText, StartNode.Nodes[0]);//Recursive Search }; StartNode = StartNode.NextNode; }; } 

这有两个部分;

  1. 将所有节点收集到List

  2. 如果搜索未更改,则通过List页面。 如果搜索已更改,请清除列表并重置索引。

我已经使用在.Net 4下运行的Windows Forms测试了它 - 它通过TreeView中的每个节点分页,其中包含搜索文本,1到1,直到它到达最后一个节点。

您需要创建节点集合(如List)并将每个找到的节点添加到该列表并返回该节点而不是单个节点。 此外,您必须删除所有break语句

我使用此搜索解决方案包含树节点上的文本

 int currentSearch = 0; int loop = 0; int found = 0; private bool FilterTreeNode(TreeNodeCollection nodes, string keyword) { bool result = false; for (int i = 0; i < nodes.Count; i++) { if(result) break; loop++; if (currentSearch < loop) { currentSearch++; if (nodes[i].Text.Contains(keyword)) { found++; _treeView.SelectedNode = nodes[i]; _treeView.SelectedNode.Expand(); _treeView.SelectedNode.EnsureVisible(); OnFindResult(string.Format("Current result: {0} on total {1} nodes. FilePath: {2}", found, _treeView.GetNodeCount(true), nodes[i].Name)); return true; } } result = FilterTreeNode(nodes[i].Nodes, keyword); } return result; }