C#中如何实现在TreeView模糊查找某一节点

第一种,递归算法,代码如下:

public TreeNode FindNode( TreeNode tnParent, string strValue )
  {

   if( tnParent == null ) return null;

   for(int i=0;i   {
    if(tnParent.Text.Substring(i,strValue.Length) == strValue && (!tnParent.Checked))
    {
     return tnParent;
    }
   }
   TreeNode tnRet = null;

   foreach( TreeNode tn in tnParent.Nodes )
   {

    tnRet = FindNode( tn, strValue );

    if( tnRet != null ) break;

   }

   return tnRet;

  }

第二种,非递归算法,代码如下:

    private TreeNode FindNode( TreeNode  tnParent, string strValue )

    {

        if( tnParent == null ) return null;

 

        if( tnParent.Nodes.Count == 0 ) return null;

 

              for(int i=0;i              {
                  if(tnParent.Text.Substring(i,strValue.Length) == strValue && (!tnParent.Checked))
                  {
                       return tnParent;
                  }

             }

        TreeNode tnCurrent, tnCurrentPar;

 

        //Init node

        tnCurrentPar = tnParent;

        tnCurrent = tnCurrentPar.FirstNode;

 

        while( tnCurrent != null && tnCurrent != tnParent )

        {

            while( tnCurrent != null )

            {

                if( tnCurrent.Text == strValue ) return tnCurrent;

                else if( tnCurrent.Nodes.Count > 0 )

                {

                    //Go into the deepest node in current sub-path

                    tnCurrentPar = tnCurrent;

                    tnCurrent = tnCurrent.FirstNode;

                }

                else if( tnCurrent != tnCurrentPar.LastNode )

                {

                    //Goto next sible node

                    tnCurrent = tnCurrent.NextNode;

                }

                else

                    break;

            }

               

            //Go back to parent node till its has next sible node

            while( tnCurrent != tnParent && tnCurrent == tnCurrentPar.LastNode )

            {

                tnCurrent = tnCurrentPar;

                tnCurrentPar = tnCurrentPar.Parent;

            }

 

            //Goto next sible node

            if( tnCurrent != tnParent )

                tnCurrent = tnCurrent.NextNode;

        }

        return null;

    }

 程序调用,如下:

private void btnSearch_Click(object sender, System.EventArgs e)
  {
   TreeNode tnRet = null;

   foreach( TreeNode tn in this.treeView.Nodes )
   {
    tnRet =  FindNode( tn,this.txtSearch.Text.Trim());
    if( tnRet != null )
    {
     tnRet.EnsureVisible();
     treeView.Select();
     treeView.SelectedNode=tnRet;
        tnRet.Checked = true;
     break;
    }
   }
   if( tnRet == null )
   {
    MessageBox.Show("查找完毕!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
   }
  }

 private void txtSearch_TextChanged(object sender, System.EventArgs e)
  {
   if(this.txtSearch.Text.Length != 0)
   {
    this.btnSearch.Enabled = true;
   }
   else
   {
    this.btnSearch.Enabled = false;
   }
  

你可能感兴趣的:(技术文档)