Populate TreeView from DataBase

前端 未结 6 1679
予麋鹿
予麋鹿 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: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:

      
                        
                          
                          
                        
                                      
    

提交回复
热议问题