递归实现treview的数据绑定

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class 药品treeview : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            bindTree();
    }

    private void bindTree()
    {
        DataTable dt = this.GetTreeData();
        this.FillNode(dt, null);
    }
    private void FillNode(DataTable dt, TreeNode node)
    {
        DataView dv = new DataView(dt);
        if (node == null)    //根结点
        {
            dv.RowFilter = "parentid='0'";  //筛选到根结点的所有子节点
        }
        else  //不是根结点
        {
            dv.RowFilter = "parentid='" + node.Value + "'";   //筛选对应节点的所有子节点
        }
        foreach (DataRowView drv in dv)   //遍历填充节点的所有子节点,如果传入的节点node为叶子节点,遍历要退出,不再进行递归
        {
            TreeNode no = new TreeNode(drv["ypmc"].ToString(), drv["ypid"].ToString());
            FillNode(dt, no);  //填充no节点的子节点
            if (node == null)
            {
                this.TreeView1.Nodes.Add(no);
            }
            else
            {
                node.ChildNodes.Add(no);
            }
        }
    }
    private DataTable GetTreeData()
    {
        string strcnn = ConfigurationManager.ConnectionStrings["strcon"].ConnectionString;
        using (SqlConnection sqlcnn = new SqlConnection(strcnn))
        {
            SqlCommand sqlcmm = sqlcnn.CreateCommand();
            sqlcmm.CommandText = "select * from T_yp";
            SqlDataAdapter da = new SqlDataAdapter(sqlcmm);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds.Tables[0];
        }
    }
}

你可能感兴趣的:(递归实现treview的数据绑定)