TreeView查获节点并选中节点

 TreeView查获节点并选中节点

 

TreeView查获节点并选中节点如果有多个节点则会继续查找下一个节点 支持关键字搜索

        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;

            }

        }


使用

 

 private List<TreeNode> CurrentNodeMatches = new List<TreeNode>();

        private int LastNodeIndex = 0;

        private string LastSearchText;



        

        private void SearchNodeText_Click(object sender, EventArgs e)

        {

            treeView1.Focus();

            string searchText = this.textBox7.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 (CurrentNodeMatches.Count == 0) MessageBox.Show("无查找记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); 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(); } else LastNodeIndex = 0; }

 

 

你可能感兴趣的:(treeview)