C#:Search from treeview

2019-09-16 10:09发布

问题:

I got a treeview data loaded from a XML file. I want to perform a search when the user types something in the textbox. Is that the right way of doing it?? I just want to filter the data. Please show me some example.

The below code is not working.

 textBox1.Enter += new EventHandler(txtSearch_TextChanged);

 private void txtSearch_TextChanged(object sender, EventArgs e)
        {

            foreach (TreeNode node in this.treeView1.Nodes)
            {

                if (node.Text.ToUpper().Contains(this.textBox1.Text.ToUpper()))
                {

                    treeView1.SelectedNode = node;

                    break;

                }
  }

回答1:

you need to register to the text changed event: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.textchanged.aspx

and for finding the specific node use:

treeView1.Nodes.Find()

mode details here: http://msdn.microsoft.com/en-us/library/system.windows.forms.treenodecollection.find



回答2:

I think another problem could be that the code you provided only looks at the top level of nodes. You would need to create a method that would recursively go through the node's child nodes until you find a match. Something like this:

private TreeNode FindNode(TreeNode node, string searchText)
{
  TreeNode result = null;

  if (node.Text == searchText)
  {
    result = node;
  }
  else
  {
    foreach(TreeNode child in node.Nodes)
    {
       result = FindNode(child, searchText);
       if (result != null)
       {
         break;
       }
    }  
  }
  return result;
}


回答3:

textBox1.Enter += new EventHandler(txtSearch_TextChanged);

 private void txtSearch_TextChanged(object sender, EventArgs e)
        {

            foreach (TreeNode node in this.treeView1.Nodes)
            {

                if (node.Text.ToUpper().Contains(this.textBox1.Text.ToUpper()))
                {
                    treeView1.Select(); // First give the focus to the treeview control,
                    //doing this, the control is able to show the selectednode.
                    treeView1.SelectedNode = node;

                    break;

                }
  }