经典 动态生成TreeView

 

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class System_MenuManage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            CreateTreeView();
            //treeMenu.Attributes.Add("oncheck", "javascript:on();");//这的oncheck没有用的,checkbox钩种不会触发。而onclick会触发
            treeMenu.Attributes.Add("onclick", "javascript:onPost()");
        }
    }
    /// <summary>
    /// 创建 TreeView 出自:http://www.cnblogs.com/Jinglecat/archive/2007/08/10/850090.html
    /// 此方法采取一次性加载目标数据到 DataTable,递归查询 DataTable ,创建子节点
    /// </summary>
    private void CreateTreeView()
    {
        //const int VirtualRootId = 0; // 虚拟的根节点 ID, 表中 ParentID=0 的节点表示无实际父节点
        const string SQL_SELECT = "SELECT Id, NodeName,ParentId FROM TreeView ORDER BY ParentId ASC";
        string connStr = ConfigurationManager.ConnectionStrings["PKConnectionString"].ConnectionString;
       
        SqlDataAdapter da = new SqlDataAdapter(SQL_SELECT, connStr);
        DataTable dt = new DataTable();
       
        da.Fill(dt);
        CreateTreeViewRecursive(treeMenu.Nodes, dt, 0);
    }

    /// <summary>
    /// 递归查询数据,创建 TreeNode 节点
    /// </summary>
    /// <param name="nodes"></param>
    /// <param name="dataSource"></param>
    /// <param name="parentId"></param>
    private void CreateTreeViewRecursive(TreeNodeCollection nodes, DataTable dataSource, int parentId)
    {
        string fliter = String.Format("ParentId={0}", parentId);
        // 查询出节点数据
        DataRow[] drArr = dataSource.Select(fliter);

        TreeNode node;
        foreach (DataRow dr in drArr)
        {
            node = new TreeNode();
            nodes.Add(node);
            // 设置属性
                node.Text = (string)dr["NodeName"];
                int nodeId = (int)dr["Id"];
                node.Value = nodeId.ToString();
                node.SelectAction = TreeNodeSelectAction.SelectExpand;
                node.ShowCheckBox = true;
            // 递归创建子节点
            CreateTreeViewRecursive(node.ChildNodes, dataSource,nodeId);
            // 移除已添加行,提高性能
            dataSource.Rows.Remove(dr);
        }
    }

你可能感兴趣的:(treeview)