TreeView递归绑定数据

本文介绍如何使用ASP.NET中的TreeView控件,并通过C#代码实现从数据库获取数据进行动态绑定。具体包括TreeView控件的基本配置、插入节点的方法及从数据库中选择数据填充到TreeView的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

界面展示如下:

        <asp:TreeView ID="TreeView1" runat="server" ImageSet="Faq" ShowLines="True">
            <HoverNodeStyle Font-Underline="True" ForeColor="Purple" />
            <NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="DarkBlue" 
                HorizontalPadding="5px" NodeSpacing="0px" VerticalPadding="0px" />
            <ParentNodeStyle Font-Bold="False" />
            <SelectedNodeStyle Font-Underline="True" HorizontalPadding="0px" 
                VerticalPadding="0px" />
        </asp:TreeView>

后台操作如下:

namespace TreeView绑定数据
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            InsertNode();
        }
        public void InsertNode()
        {
            Class1 cl = new Class1();
            DataTable dt = cl.ext_Table();
            SearchNode(TreeView1.Nodes,dt,"0");
        }
        public void SearchNode(TreeNodeCollection nodes, DataTable ds, string parentid)
        {
            string pnodekey;
            pnodekey = string.Format("parentid={0}", parentid);
            DataRow[] drs = ds.Select(pnodekey);
            TreeNode node;
            foreach (DataRow dr in drs)
            {
                node = new TreeNode();
                node.Text = (string)dr["Name"];
                node.Value = dr["id"].ToString();
                nodes.Add(node);
                SearchNode(node.ChildNodes,ds, node.Value);
            }


        }
    }
}

Class1类展示如下:

public class Class1
    {
        //在"配置文件"中读起连接字符串
        public string ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        public DataTable ext_Table()
        {
            OleDbConnection myConnection = new OleDbConnection(ConnectionString);
            myConnection.Open();
            OleDbCommand selectCommand = new OleDbCommand("select *  from  C_Word", myConnection);

            OleDbDataAdapter da = new OleDbDataAdapter(selectCommand);

            DataSet ds = new DataSet();

            da.Fill(ds);

            myConnection.Close();

            return ds.Tables[0];
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值