Treeview from sql table

后端 未结 2 682
忘掉有多难
忘掉有多难 2021-01-12 08:29

I have sql table like below. I have to show it in tree view

id   parentid     name
1     NULL       outlook
2     1      overcast
3     1       rainy
4     1         


        
2条回答
  •  灰色年华
    2021-01-12 09:27

    Try the following code in your aspx or ascx file:

    
    

    And in the codebehind to populate it:

    private void PopulateTreeView()
    {
        DataSet ds = new DataSet(); //(populate the dataset with the table)
    
        //Use LINQ to filter out items without a parent
        DataTable parents = ds.Tables[0].AsEnumerable()
            .Where(i => i.Field("parentid") == DBNull.Value)
            .CopyToDataTable();
    
        //Use LINQ to filter out items with parent
        DataTable children = ds.Tables[0].AsEnumerable()
            .Where(i => i.Field("parentid") != DBNull.Value)
            .OrderBy(i => i.Field("parentid"))
            .CopyToDataTable();
    
        //Add the parents to the treeview
        foreach(DataRow dr in parents)
        {
            TreeNode node = new TreeNode();
            node.Text = dr["name"].ToString();
            node.Value = dr["id"].ToString();
            TreeView1.Nodes.Add(node);
        }
    
        //Add the children to the parents
        foreach(DataRow dr in children)
        {
            TreeNode node = new TreeNode();
            node.Text = dr["name"].ToString();
            node.Value = dr["id"].ToString();
            TreeNode parentNode = FindNodeByValue(dr["parentid"].ToString());
            if(parentNode != null)
                parentNode.ChildNodes.Add(node);
        }
    }
    
    private TreeNode FindNodeByValue(string value)
    {
        foreach(TreeNode node in TreeView1.Nodes)
        {
            if(node.Value = value) return node;
            TreeNode pnode = FindNodeRecursion(node, value);
            if(pnode != null) return pnode;
        }
        return null;
    }
    
    private TreeNode FindNodeRecursion(TreeNode parentNode, string value)
    {
        foreach(TreeNode node in parentNode.ChildNodes)
        {
            if(node.Value = value) return node;
            TreeNode pnode = FindNodeRecursion(node, value);
            if(pnode != null) return pnode;
        }
        return null;
    }
    
    
    

    There might be a better way to do this and I haven't tested it, but it should work. Or you could always try out Telerik or another third party tool that makes data binding for these types of controls super easy.

    提交回复
    热议问题