Skip to main content
 首页 » 编程设计

c#之如何使用 Asp.net 在 TreeView 中动态添加根节点

2024年02月13日13itcoder

我想将 DataTable 绑定(bind)到 TreeView。我已经编写了以下代码。它目前正在工作,意味着它显示 DataTable 的所有数据但没有根节点。

 List<DocumentData> lstData = GetSPDocuments(); 
    gvDocuments.DataSource = lstData; 
    gvDocuments.DataBind(); 
 
    DataTable dt = ConvertToDataTable(lstData); 
 
    TreeNode node1 = new TreeNode("Root"); 
 
 
    foreach (DataRow r in dt.Rows) 
    { 
        int nodeLvl = int.Parse(r["ID"].ToString()); 
        string nodeParent = "Folders"; 
        string nodeName = r["Title"].ToString(); 
 
 
        TreeNode tNode = new TreeNode(nodeName); 
 
        ht.Add(nodeLvl.ToString() + nodeName, tNode); 
 
        if (tvDocs.Nodes.Count == 0) 
            tvDocs.Nodes.Add(tNode); 
        else 
        { 
            nodeLvl--; 
            tvDocs.Nodes.Add(tNode);                
        } 
    } 

如何在这里添加静态根节点???请帮忙!

请您参考如下方法:

试试这个,也许它能帮到你。

 protected void Page_Load(object sender, EventArgs e) 
    { 
        conStr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString; 
        conn = new OleDbConnection(conStr); 
        BindTreeViewControl(); 
    } 
 
    private void BindTreeViewControl() 
    { 
        try 
        { 
            DataSet ds = GetDataSet("Select ProductId,ProductName,ParentId from ProductTable"); 
            DataRow[] Rows = ds.Tables[0].Select("ParentId = 0");  
 
            for (int i = 0; i < Rows.Length; i++) 
            { 
                TreeNode root = new TreeNode(Rows[i]["ProductName"].ToString(), Rows[i]["ProductId"].ToString()); 
                root.SelectAction = TreeNodeSelectAction.Expand; 
                CreateNode(root, ds.Tables[0]); 
                treeviwExample.Nodes.Add(root); 
            } 
        } 
        catch (Exception Ex) { throw Ex; } 
    } 
 
    public void CreateNode(TreeNode node, DataTable Dt) 
    { 
        DataRow[] Rows = Dt.Select("ParentId =" + node.Value); 
        if (Rows.Length == 0) { return; } 
        for (int i = 0; i < Rows.Length; i++) 
        { 
            TreeNode Childnode = new TreeNode(Rows[i]["ProductName"].ToString(), Rows[i]["ProductId"].ToString()); 
            Childnode.SelectAction = TreeNodeSelectAction.Expand; 
            node.ChildNodes.Add(Childnode); 
            CreateNode(Childnode, Dt); 
        } 
    } 
    private DataSet GetDataSet(string Query) 
    { 
        DataSet Ds = new DataSet(); 
        try 
        { 
            OleDbDataAdapter da = new OleDbDataAdapter(Query, conn); 
            da.Fill(Ds); 
        } 
        catch (Exception dex) { } 
        return Ds; 
    } 

数据库结构是