Populate TreeView from DataBase

前端 未结 6 1669
予麋鹿
予麋鹿 2020-12-02 15:14

I have a database table (named Topics) which includes these fields :

  1. topicId
  2. name
  3. parentId

and by using them I wanna populate

相关标签:
6条回答
  • 2020-12-02 15:25

    It will probably be something like this. Give some more detail as to what exactly you want to do if you need more.

    //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);
         }
    
     }
    
    0 讨论(0)
  • 2020-12-02 15:25

    When there are no Large Amounts of Data then it is not good to connect database, fetch data and add to treeview node again and again for child/sub nodes. It can be done in single attempt. See following sample:
    http://urenjoy.blogspot.com/2009/08/display-hierarchical-data-with-treeview.html

    0 讨论(0)
  • 2020-12-02 15:31

    This code runs perfectly for me. Thought it might be useful for somebody looking to display hierarchial data in a treeview.By far, i guess this is the simplest. Please check it out and upvote if it helps you.

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

    C# code:

     //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 code:

    <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> 
    
    0 讨论(0)
  • 2020-12-02 15:36
    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-02 15:46

    Not quite.

    Trees are usually handled best by not loading everything you can at once. So you need to get the root node (or topic) which has no parentIDs. Then add them to the trees root node and then for each node you add you need to get its children.

    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);
    }
    
    0 讨论(0)
  • 2020-12-02 15:47

    this code runs perfectly for me, check it out i think it will help you :)

    ;

    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;
    }
    
    0 讨论(0)
提交回复
热议问题