从数据库填充 TreeView

Posted

技术标签:

【中文标题】从数据库填充 TreeView【英文标题】:Populate TreeView from DataBase 【发布时间】:2010-09-26 13:47:59 【问题描述】:

我有一个包含以下字段的数据库表(名为主题):

    主题标识 姓名 父ID

通过使用它们,我想在 c# 中填充 TreeView。我该怎么做?

提前谢谢...

【问题讨论】:

【参考方案1】:

大概是这样的。如果您需要更多,请详细说明您想要做什么。

//In Page load
foreach (DataRow row in topics.Rows)

    TreeNode node = new TreeNode(dr["name"], dr["topicId"])
    node.PopulateOnDemand = true;

     TreeView1.Nodes.Add(node);
 
 ///
 protected void PopulateNode(Object sender, TreeNodeEventArgs e)
 
     string topicId = e.Node.Value;
     //select from topic where parentId = topicId.
     foreach (DataRow row in topics.Rows)
     
         TreeNode node = new TreeNode(dr["name"], dr["topicId"])
         node.PopulateOnDemand = true;

         e.Node.ChildNodes.Add(node);
     

 

【讨论】:

【参考方案2】:

不完全是。

通常最好不要一次加载所有可以加载的内容来处理树。因此,您需要获取没有 parentID 的根节点(或主题)。然后将它们添加到树根节点,然后对于您添加的每个节点,您需要获取它的子节点。

foreach (DataRow row in topicsWithOutParents.Rows)

   TreeNode node = New TreeNode(... whatever);
   DataSet childNodes = GetRowsWhereParentIDEquals(row["topicId"]);
   foreach (DataRow child in childNodes.Rows)
    
       Treenode childNode = new TreeNode(..Whatever);
       node.Nodes.add(childNode);
   
   Tree.Nodes.Add(node);

【讨论】:

【参考方案3】:

这段代码对我来说运行得很好,检查一下我认为它会对你有所帮助:)

;

protected void Page_Load(object sender, EventArgs e)

    DataSet ds = RunQuery("Select topicid,name from Topics where Parent_ID IS NULL");
       for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        
           TreeNode root = new TreeNode(ds.Tables[0].Rows[i][1].ToString(),ds.Tables[0].Rows[i][0].ToString());
           root.SelectAction = TreeNodeSelectAction.Expand;
           CreateNode(root);
           TreeView1.Nodes.Add(root);
       




void CreateNode(TreeNode node)

    DataSet ds = RunQuery("Select topicid, name from Category where Parent_ID =" + node.Value);
    if (ds.Tables[0].Rows.Count == 0)
    
        return;
    
    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
    
        TreeNode tnode = new TreeNode(ds.Tables[0].Rows[i][1].ToString(), ds.Tables[0].Rows[i][0].ToString());
        tnode.SelectAction = TreeNodeSelectAction.Expand;
        node.ChildNodes.Add(tnode);
        CreateNode(tnode);
    


DataSet RunQuery(String Query)

    DataSet ds = new DataSet();
    String connStr = "???";//write your connection string here;
    using (SqlConnection conn = new SqlConnection(connStr))
    
        SqlCommand objCommand = new SqlCommand(Query, conn);
        SqlDataAdapter da = new SqlDataAdapter(objCommand);
        da.Fill(ds);
        da.Dispose();
    
    return ds;

【讨论】:

旧帖,但很有用。无论如何,单击节点时如何获取值?干杯,【参考方案4】:
protected void Page_Load(object sender, EventArgs e)

    if (!Page.IsPostBack)
        PopulateRootLevel();



private void PopulateRootLevel()

    SqlConnection objConn = new SqlConnection(connStr);
    SqlCommand objCommand = new SqlCommand(@"select FoodCategoryID,FoodCategoryName,(select count(*) FROM FoodCategories WHERE ParentID=c.FoodCategoryID) childnodecount FROM FoodCategories c where ParentID IS NULL", objConn);
    SqlDataAdapter da = new SqlDataAdapter(objCommand);
    DataTable dt = new DataTable();
    da.Fill(dt);
    PopulateNodes(dt, TreeView2.Nodes);


private void PopulateSubLevel(int parentid, TreeNode parentNode)

    SqlConnection objConn = new SqlConnection(connStr);
    SqlCommand objCommand = new SqlCommand(@"select FoodCategoryID,FoodCategoryName,(select count(*) FROM FoodCategories WHERE ParentID=sc.FoodCategoryID) childnodecount FROM FoodCategories sc where ParentID=@parentID", objConn);
    objCommand.Parameters.Add("@parentID", SqlDbType.Int).Value = parentid;
    SqlDataAdapter da = new SqlDataAdapter(objCommand);
    DataTable dt = new DataTable();
    da.Fill(dt);
    PopulateNodes(dt, parentNode.ChildNodes);



protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)

    PopulateSubLevel(Int32.Parse(e.Node.Value), e.Node);


private void PopulateNodes(DataTable dt, TreeNodeCollection nodes)

    foreach (DataRow dr in dt.Rows)
    
        TreeNode tn = new TreeNode();
        tn.Text = dr["FoodCategoryName"].ToString();
        tn.Value = dr["FoodCategoryID"].ToString();
        nodes.Add(tn);

        //If node has child nodes, then enable on-demand populating
        tn.PopulateOnDemand = ((int)(dr["childnodecount"]) > 0);
    

【讨论】:

【参考方案5】:

当没有大量数据时,连接数据库,获取数据并为子/子节点一次又一次地添加到树视图节点是不好的。它可以在一次尝试中完成。请参阅以下示例:http://urenjoy.blogspot.com/2009/08/display-hierarchical-data-with-treeview.html

【讨论】:

【参考方案6】:

这段代码对我来说运行完美。认为它可能对希望在树视图中显示层次结构数据的人有用。到目前为止,我想这是最简单的。如果对您有帮助,请查看并点赞。

参考:https://techbrij.com/display-hierarchical-data-with-treeview-in-asp-net

C#代码:

 //dtTree  should be accessible in both page load and AddNodes()
    //DocsMenu is the treeview Id
          DataTable dtTree = new DataTable(); 
//declare your connection string
                protected void Page_Load(object sender, EventArgs e)
                
                    //DataTable dtTree = new DataTable();
                    using (con)
                    
                        con.Open();

                        string sQuery = "Select topicId,parentid,name from tbl_topicMaster";
                        SqlCommand cmd = new SqlCommand(sQuery, con);
                        cmd.CommandType = CommandType.Text;
                        SqlDataAdapter da = new SqlDataAdapter(cmd);
                        da.Fill(dtTree);
                        da.Dispose();
                        con.Close();
                    

                    AddNodes(-1, DocsMenu.Nodes);
                




                void AddNodes(int id, TreeNodeCollection tn)
                
                    foreach (DataRow dr in dtTree.Select("parentid= " + id))
                    
                        TreeNode sub = new TreeNode(dr["name"].ToString(), dr["topicId"].ToString());
                        tn.Add(sub);
                        AddNodes(Convert.ToInt32(sub.Value), sub.ChildNodes);
                    
                

aspx代码:

<asp:TreeView ID="DocsMenu" runat="server" ImageSet="BulletedList" 
        NodeIndent="15"  >  
                    <HoverNodeStyle Font-Underline="True" ForeColor="#6666AA" />
                    <NodeStyle Font-Names="Tahoma" Font-Size="8pt" ForeColor="Black" HorizontalPadding="2px"  
                        NodeSpacing="0px" VerticalPadding="2px"></NodeStyle>  
                    <ParentNodeStyle Font-Bold="False" />  
                    <SelectedNodeStyle BackColor="#B5B5B5" Font-Underline="False" HorizontalPadding="0px"  
                        VerticalPadding="0px" />
                                 </asp:TreeView> 

【讨论】:

以上是关于从数据库填充 TreeView的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 JSON 数据递归填充 TreeView

从另一个类填充TreeView(或更好的东西?)C#

C#编程,TreeView控件的学习

无法为填充的 TreeView 节点触发 SelectedNodeChanged 事件

Gtk+ 删除 Gtk::Treeview 上第一列的填充/边距

如何在 TreeView 中禁用或修改 TreeCell 的填充