生成树的递归实现

类别:.NET开发 点击:0 评论:0 推荐:

当然先要有第三方的TREEVIEW控件:)
using Microsoft.Web .UI .WebControls ;


private void InitTree(TreeNodeCollection nds,string mailfrom,long time)
  {
   //创建一个数据试图
   DataView dv=new DataView ();
   //创建一个新节点
   TreeNode tempnd=new TreeNode ();
   //给数据试图添加值
   dv.Table =dataset.Tables ["tree"];
   //试图过滤
   //dv.RowFilter ="MailFrom='" +mailfrom+ "'";
   al.Add (mailfrom);

   //关闭dataset
   dataset.Clear ();
   dataset.Dispose ();
   myconnection.Close ();
   myconnection.Dispose ();

   
  
   foreach(DataRowView drv in dv)
   {
    //从试图中获取节点信息
    tempnd=new TreeNode ();
    //获取节点的ID
    tempnd.ID =drv["MailSrc"].ToString ();
    //获取节点的TEXT
    tempnd.Text =drv["MailSrc"].ToString ();
    //获取捕捉时间
    string tempnddt=drv["capturetime"].ToString() ;
    //将时间转换为LONG便于比较
    long temp=long.Parse (tempnddt);

    //判定该节点是否可以加入(是否已经存在该节点或者捕捉时间小于父节点的捕捉时间
    if(al.Contains (tempnd.Text ) || time>temp)
     continue;
    else
    {
     //将该节点加入已存在节点处
     al.Add (tempnd.Text );
     //树中加入节点
     nds.Add (tempnd);
     //递归
     //设置新的数据集
     string tempndtxt=tempnd.Text ;
     myconnection=new System.Data.SqlClient.SqlConnection ("server=localhost;uid=sa;pwd=sa;database=zhltest");
     myconnection.Open ();
     mycommand=new System.Data.SqlClient.SqlCommand ();
     mycommand.Connection =myconnection;
     mycommand.CommandText ="select * from testmail where MailFrom='" +tempndtxt+ "'";
     adapter=new System.Data.SqlClient.SqlDataAdapter (mycommand.CommandText ,myconnection);
     dataset=new DataSet ();
     //将满足条件的存入dataset中
     adapter.Fill (dataset,"tree");
     
     InitTree(tempnd.Nodes,tempnd.ID,temp);
     
                  
    }
   }


private void Button1_Click(object sender, System.EventArgs e)
  {
   string query=treetxt.Text ;
   myconnection=new System.Data.SqlClient.SqlConnection ("server=localhost;uid=sa;pwd=sa;database=zhltest");
   myconnection.Open ();
   mycommand=new System.Data.SqlClient.SqlCommand ();
   mycommand.Connection =myconnection;
   mycommand.CommandText ="select * from testmail where MailFrom='" +query+ "'";
   adapter=new System.Data.SqlClient.SqlDataAdapter (mycommand.CommandText ,myconnection);
   dataset=new DataSet ();
   //将满足条件的存入dataset中
   adapter.Fill (dataset,"tree");
   InitTree(TreeView1.Nodes ,query,0);
  }

本文地址:http://com.8s8s.com/it/it43427.htm