这里使用TreeNodePopulate事件加载各个节点,下面列出步骤: 1.假设有一个下面类似的类,一个简单的无限极分类的结构: class Category { public string id { get; set; } public string name { get; set; } public string parentid { get; set; } } 为了演示方便,列出一些模拟数据; List<Category> list = null; Category c1 = new Category { id = "1", name = "设计部门", parentid = "0" }; Category c2 = new Category { id = "2", name = "薪酬部门", parentid = "1" }; Category c3 = new Category { id = "3", name = "后勤部门", parentid = "1" }; Category c4 = new Category { id = "4", name = "会计部门", parentid = "0" }; Category c5 = new Category { id = "5", name = "慧眼部门", parentid = "4" }; Category c6 = new Category { id = "6", name = "模特部门", parentid = "4" }; Category c7 = new Category { id = "7", name = "交流中心", parentid = "0" }; Category c8 = new Category { id = "8", name = "会议交流", parentid = "0" }; list = new List<Category> { c1,c2,c3,c4,c5,c6,c7,c8 }; 假设我们页面上要使用的控件ID为TreeView1; 在页面加载时候为其注册事件: TreeView1.TreeNodePopulate += new TreeNodeEventHandler(TreeView1_TreeNodePopulate); 接下来我们手动写上树的根节点: TreeNode tn = new TreeNode(); tn.Text = "公司栏目"; tn.Value = "0"; TreeNodeEventArgs args = new TreeNodeEventArgs(tn); TreeView1_TreeNodePopulate(TreeView1, args);//这里去调用事件绑定节点 TreeView1.Nodes.Add(tn); ///////// void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e) { List<Category> li = list.Where(x => x.parentid == e.Node.Value).ToList(); foreach (Category c in li) { TreeNode n = new TreeNode(); n.Text = c.name; n.Value = c.id; n.PopulateOnDemand = true;//注意这个属性设置 n.NavigateUrl = "files.aspx?folder; n.SelectAction = TreeNodeSelectAction.Expand; e.Node.ChildNodes.Add(n); } } OK了。当然也完全可以递归去append各个节点。
|
请发表评论