zjk20108023的专栏

案例需求:动态将一个公司各个部门按照部门顺序排列,在页面动态生成列表,,并且子级部门需要比父级部门缩进20px。

页面代码:

<div><asp:Button ID="btnCreate" runat="server" onclick="btnCreate_Click" Text="生成" /><asp:Literal ID="Literal1" runat="server"></asp:Literal></div>后台代码:

1、

public class Department{public Department(int id, string name, int parentid){this.Id = id;this.Name = name;this.ParentId = parentid;}public int Id { get; set; }public string Name { get; set; }public int ParentId { get; set; }}2、

List<Department> listTc = new List<Department>();public void LoadData(){listTc.Add(new Department(1, "财务部", 2));listTc.Add(new Department(2, "公司总部", 0));listTc.Add(new Department(3, "财务组1", 1));listTc.Add(new Department(4, "财务组2", 1));listTc.Add(new Department(5, "研发部", 2));listTc.Add(new Department(6, "研发组1", 5));listTc.Add(new Department(7, "研发组2", 5));listTc.Add(new Department(8, "研发组3", 5));listTc.Add(new Department(9, "业务部", 2));listTc.Add(new Department(10, "业务组1", 9));listTc.Add(new Department(11, "业务组2", 9));listTc.Add(new Department(12, "业务组3", 9));listTc.Add(new Department(13,"研发组1第一小组",6));listTc.Add(new Department(14, "业务组1第一小组", 10));listTc.Add(new Department(15, "研发组1第二小组", 6));listTc.Add(new Department(16, "研发组1第二小组1", 15));listTc.Add(new Department(17, "研发组1第二小组2", 15));}3、

List<Department> tempList = new List<Department>();public List<Department> Sort(int parentId){var tcList = GetListTC(parentId);if (tempList.Count < listTc.Count){if (tcList.Count > 0){foreach (var tc in tcList){if (!tempList.Contains(tc)){tempList.Add(tc);return Sort(tc.Id);}}var t = GetTC(parentId);return Sort(t.ParentId);}else{var tc = GetTC(parentId);return Sort(tc.ParentId);}}else{return tempList;}}4、

public int GetLevel(Department tc,int level){var t = listTc.Find(o => o.Id == tc.ParentId);if (t!=null){level++;return GetLevel(t,level);}return level;}public List<Department> GetListTC(int parentId){var list = listTc.FindAll(o =>o.ParentId == parentId);return list;}public Department GetTC(int id){var tc = listTc.Find(o => o.Id == id);return tc;}        public string InitHtml(int level, string name)        {            string html = string.Empty;            html += "<li style='margin-left:" + level* 20 + "px'>" + name + "</li>";            return html;        }5、public string CreateHtml(){var list = Sort(0);string strHtml = string.Empty;foreach (var tc in list){int lev = GetLevel(tc, 0);strHtml += InitHtml(lev, tc.Name);}return strHtml;}6、

protected void btnCreate_Click(object sender, EventArgs e){LoadData();this.Literal1.Text = CreateHtml();}

思路:先将数据排序好,根据当前单位的级别数生成li.

页面效果图:

你被雨淋湿的心,是否依旧。

zjk20108023的专栏

相关文章:

你感兴趣的文章:

标签云: