TreeView控件递归绑定数据学习

将表中的字段封装成属性:文件名(Demo_Area.cs)

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

/// <summary>
///Demo_Area 的摘要说明
/// </summary>
public class Demo_Area
{
 public Demo_Area()
 {
  //
  //TODO: 在此处添加构造函数逻辑
  //
 }
    private int id;
    private string name;
    private int pid;

    public int Pid
    {
        get { return pid; }
        set { pid = value; }
    }

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public int Id
    {
        get { return id; }
        set { id = value; }
    }

}

 

页面中的代码:

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

public partial class TreeView : System.Web.UI.Page
{

    //连接数据库
    private static string connstr = System.Configuration.ConfigurationManager.ConnectionStrings["ConnStr"].ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
            return;
        BindTree("0");
    }

    #region 绑定父节点(第一级)
    private void BindTree(string pid)
    {
        DataSet ds = GetData(pid);
        if (ds.Tables[0].Rows.Count > 0)
        {
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                TreeNode node = new TreeNode();
                node.Text = ds.Tables[0].Rows[i]["Name"].ToString();
                node.Value = ds.Tables[0].Rows[i]["ID"].ToString();
                this.TreeView1.Nodes.Add(node);
                BindNode(node);
            }
        }
    }
    #endregion

    #region 绑定子节点
    private void BindNode(TreeNode nd)
    {
        DataSet ds = GetData(nd.Value);
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            TreeNode node = new TreeNode();
            node.Text = ds.Tables[0].Rows[i]["Name"].ToString();
            node.Value = ds.Tables[0].Rows[i]["ID"].ToString();

            nd.ChildNodes.Add(node);

            BindNode(node);
        }
    }
    #endregion

    #region 将父级下的子级查询出来,并返回一张虚拟表
    private DataSet GetData(string pid)
    {
        SqlConnection con = new SqlConnection(connstr);
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter("select * from Area_MS where Pid=" + pid, con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        return ds;
    }
    #endregion

}

效果图:

posted @ 2010-10-19 07:55  _YMW  阅读(2540)  评论(0编辑  收藏  举报