导航树代码

来源:互联网 发布:java string转byte 编辑:程序博客网 时间:2024/05/22 21:46

一个表存储父子模块的情况:
public class Tree : System.Web.UI.Page
 {
  protected Microsoft.Web.UI.WebControls.TreeView TreeView1;
  string strcn = "workstation id=PROJECT3;packet size=4096;user id=sa;data source=/"PROJECT3//PROJECT" +
    "3/";persist security info=False;initial catalog=tree; min pool size=2;max pool size=5";

  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   SqlConnection _Sqlconnection1 = new SqlConnection(strcn);
   string str1 = "select * from t_tree";
   _Sqlconnection1.Open();
   SqlCommand _Sqlcommand1 = new SqlCommand(str1,_Sqlconnection1);
   SqlDataAdapter dr=new SqlDataAdapter(_Sqlcommand1);
   DataSet da1=new DataSet();
   dr.Fill(da1);
   //ViewState  获取状态信息的字典,
   //这些信息使您可以在同一页的多个请求间保存和还原服务器控件的视图状态。
   this.ViewState["ds"]=da1;
   _Sqlconnection1.Close();
   Gettreestruct(0,(TreeNode)null);
  
  }
  /// <summary>
  /// 导航树的递归算法
  /// </summary>
  /// <param name="id"></param>
  /// <param name="t1"></param>
  public void Gettreestruct(int id,TreeNode t1)
  {
   DataSet da =(DataSet)this.ViewState["ds"];
   DataView trr = new DataView(da.Tables[0]);
   trr.RowFilter="[parentid]="+id;
   foreach(DataRowView row in trr)
   {
     TreeNode nod=new TreeNode();
    if(t1==null)
    {
     nod.Text=row["mytext"].ToString();
     TreeView1.Nodes.Add(nod);
     //Expanded属性决定是否展开树
     nod.Expanded = true;
     Gettreestruct(Int32.Parse(row["nodeid"].ToString()),nod);
    }
    else
    {
     nod.Text =row["mytext"].ToString();
     t1.Nodes.Add(nod);
     nod.Expanded = true;
     Gettreestruct(Int32.Parse(row["nodeid"].ToString()),nod);    
    }

   }

  }
两个表关联存放父子模块的情况:
public void LoadTree()
  {
   DataSet da =(DataSet)this.ViewState["ds"];
   int count=0;
   foreach(DataRow row in da.Tables["Main"].Rows)
   {
    
    TreeNode nod=new TreeNode() ;
    nod.Text=row["MainName"].ToString();
    this.TreeView1.Nodes.Add(nod);

    DataView trr = new DataView(da.Tables["Sub"]);
    trr.RowFilter="MainID='"+row["MainID"].ToString()+"'";

    for(int i=0;i<trr.Count;i++)
    {
     TreeNode nod1=new TreeNode();
     nod1.Text=trr[i]["SubName"].ToString();
     this.TreeView1.Nodes[count].Nodes.Add(nod1);     
    }
    count++; 
   }
  }

原创粉丝点击