Recursive TreeView in ASP.NET

前端 未结 3 2024
梦如初夏
梦如初夏 2020-11-30 09:27

I have an object of type list from which I wish to use to populate a treeview in asp.net c#.

Each object item has:

id | Name | ParentId
3条回答
  •  [愿得一人]
    2020-11-30 09:47

        //In load for example
        if (!IsPostBack)
        {
                DataSet ds = new DataSet();
                ds = getRoles(); //function that gets data collection from db.
    
                tvRoles.Nodes.Clear();
    
                BindTree(ds, null); 
                tvRoles.DataBind();
    
        }       
    
        private void BindTree(DataSet ds, TreeNode parentNode)
        {
            DataRow[] ChildRows;
            if (parentNode == null)
            {
                string strExpr = "ParentId=0";
                ChildRows = ds.Tables[0].Select(strExpr);                    
            }
            else
            {
                string strExpr = "ParentId=" + parentNode.Value.ToString();
                ChildRows = ds.Tables[0].Select(strExpr); 
            }   
            foreach (DataRow dr in ChildRows)
            {
                TreeNode newNode = new TreeNode(dr["Name"].ToString(), dr["Id"].ToString());
                if (parentNode == null)
                {
                    tvRoles.Nodes.Add(newNode);
                }
                else
                {
                    parentNode.ChildNodes.Add(newNode);
                }
                BindTree(ds, newNode);
            }
        }
    

提交回复
热议问题