asp.net 2.0 treeview控件“简单”操纵

这几天正在学asp.net2.0的,虽然还只是测试版,但听说很早就出来了,我也是前一个月才听说,有点

惭愧。她的变化实在太大了,其中就有多了一个树形控件treeview,在1.0中是要自己下载安装的,可见

2.0是更加的完善了。因为是一个控件,所以静态填充用起来还是很简单的,设置一些属性就OK了,但是

要动态地添加就只好自己写代码了,方法和1.0差不多,我研究了两天,总算有了点结果,嘿,太感

动....
--------------------------------------------------------------------------------
具体步骤如下:
一、从工具箱中拖一个treeview控件设置如下属性
   OnTreeNodePopulate="Node_Populate" //调用后台的一个方法
   ID="tree"
 >
  
     Value="0" />
  

二、建立数据库用来存放各节点信息,数据库表如下

三、动态读取数据。在aspx.cs文件中实现
public void Node_Populate(object sender, System.Web.UI.WebControls.TreeNodeEventArgs e)
    {
        if (e.Node.ChildNodes.Count == 0)//判断是否当前为第一级节点
        {
            switch (e.Node.Depth)//获取节点的深度
            {
                case 0:
                    Fill_Fathers(e.Node);//促发事件,并传递引发事件的节点!
                    break;
                case 1:
                    Fill_Childs(e.Node);
                    break;
            }
        }
    }


void Fill_Fathers(TreeNode node)//列出父节点
   {  //创建数据库连接并把数据缓存到dataset Tree_father表中
       string connString = ConfigurationManager.ConnectionStrings

["EnglishConnectionString"].ConnectionString;
       SqlConnection connection = new SqlConnection(connString);
       SqlCommand command = new SqlCommand("Select Father_name From  Tree_father where

Father_id is null", connection);
       SqlDataAdapter adapter = new SqlDataAdapter(command);
       DataSet Tree_father = new DataSet();
       adapter.Fill(Tree_father);
   if (Tree_father.Tables.Count > 0)
   {
       foreach (DataRow row in Tree_father.Tables[0].Rows)//循环列出父节点
   {
   TreeNode newNode = new TreeNode(row["Father_name"].ToString());
   //        + "" +
   //row["Father_name"].ToString(),
   //row["Father_id"].ToString());
   newNode.PopulateOnDemand = true;
   newNode.SelectAction = TreeNodeSelectAction.Expand;
   node.ChildNodes.Add(newNode);
   }
   }
   }


 void Fill_Childs(TreeNode node)
   {
   string author = node.Value.ToString();
   string connString = ConfigurationManager.ConnectionStrings

["EnglishConnectionString"].ConnectionString;
   SqlConnection connection = new SqlConnection(connString);//注意数据类型!!!下面用

like!!
   SqlCommand command = new SqlCommand("Select Father_name,id from Tree_father where

Father_id like '"+author+"'", connection);
   SqlDataAdapter adapter = new SqlDataAdapter(command);
   DataSet titlesForAuthors = new DataSet();
   adapter.Fill(titlesForAuthors);
   if (titlesForAuthors.Tables.Count > 0)
   {
   foreach (DataRow row in titlesForAuthors.Tables[0].Rows)
   {
   TreeNode newNode = new TreeNode(row["Father_name"].ToString());
   newNode.PopulateOnDemand = true;
   newNode.NavigateUrl = "../admin/switch.aspx?classId=" + row["ID"].ToString();
   //newNode.Target = "mainfram";
   newNode.SelectAction = TreeNodeSelectAction.Select;
   node.ChildNodes.Add(newNode);
   }
   }
   }
以上例子测试成功。

原文地址:https://www.cnblogs.com/footleg/p/910012.html