C#:Search from treeview

99封情书 提交于 2019-12-25 03:49: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;

                }
  }


来源:https://stackoverflow.com/questions/11084027/csearch-from-treeview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!