TreeView 绑定数据库应用

表字段:userid,username,superiorid

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class BossCenter_ReserveDetail : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.UrlReferrer != null)
                ViewState["UrlReferrer"] = Request.UrlReferrer.ToString();
            //----------属性框 显示用户列表------------
            string sql = "select userid,username,superiorid from b_userlist";
            System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(SqlHelper.strConnectionString);
            System.Data.SqlClient.SqlDataAdapter sda = new System.Data.SqlClient.SqlDataAdapter(sql, con);
            DataSet dsTree = new DataSet();
            sda.Fill(dsTree);
            //调用方法构件树形目录
            BuildTree(TreeView1, dsTree);
        }
    }

    public bool BuildTree(TreeView tv, DataSet ds)
    {
        tv.Nodes.Clear();

        foreach (DataRow dbRow in ds.Tables[0].Rows)
        {
            if (dbRow["superiorid"].ToString() == "0" || dbRow["superiorid"].ToString() == "2")
            {
                dbRow["superiorid"] = DBNull.Value;
            }
        }
        ds.Relations.Add("NodeRelation", ds.Tables[0].Columns["userid"], ds.Tables[0].Columns["superiorid"], false);

        foreach (DataRow dbRow in ds.Tables[0].Rows)
        {
            if (dbRow.IsNull("superiorid"))
            {
                TreeNode newNode = CreateNode(dbRow["username"].ToString(), dbRow["userid"].ToString());

                tv.Nodes.Add(newNode);
                PopulateSubTree(dbRow, newNode);
            }
        }

        //展开所有节点
        tv.ExpandAll();

        return true;
    }

    private void PopulateSubTree(DataRow dbRow, TreeNode node)
    {
        foreach (DataRow childRow in dbRow.GetChildRows("NodeRelation"))
        {
            TreeNode childNode = CreateNode(childRow["username"].ToString(), childRow["userid"].ToString());
            node.ChildNodes.Add(childNode);
            PopulateSubTree(childRow, childNode);
        }
    }

    private TreeNode CreateNode(string text, string tag)
    {
        TreeNode node = new TreeNode();
        node.Text = text;
        node.Target = tag;
        return node;
    }

}

 

如果要刷新页面保持treeview1保持展开保持选中,就得记录当前选中节点,找根节点时通过valuepath查找,然后展开

string[] paths=tn.ValuePath.Split(',');

        TreeNode tn2 = TreeView1.FindNode(paths[0]);
        tn2.ExpandAll();
        TreeNode tn3 = TreeView1.FindNode(tn.ValuePath);
        tn3.Selected = true;

你可能感兴趣的:(treeview)