how to populate treeview?

前端 未结 3 1013
醉酒成梦
醉酒成梦 2021-01-24 18:59

I have a table \"Category\".It is simply a table of users, where each are identified with a unique UserId and have a corresponding ParentId (pointing to their boss\' UserId). I

3条回答
  •  -上瘾入骨i
    2021-01-24 19:21

    I guess you know how to read data from database so I skip that part.

    An abstract version - you could read the employees from any source.

    Some helper entities (you can do without them ofc - it is just easier/nicer to use this way):

    /// The employee structure with explicit conversion to a TreeNode (you may also use implicit conversion, but i prefer explicit).
    public struct Employee
    {
        public int Id;
        public string Name;
        public int BossId;
    
        public static explicit operator TreeNode(Employee e) { return new TreeNode(e.Name); }
    }
    
    public static class EmployeesExtension
    {
        /// More abstract and readable way to add an employee.
        public static void Add(this Dictionary> employees, int id, string name, int bossId)
        {
            if (!employees.ContainsKey(bossId)) employees[bossId] = new List();
    
            employees[bossId].Add(new Employee() { Id = id, Name = name, BossId = bossId });
        }
    }
    

    The method used to populate a TreeView:

    public static void PopulateTreeView(Dictionary> employees, int bossId, TreeNodeCollection nodes)
    {
        if (!employees.ContainsKey(bossId)) return;
    
        foreach (Employee e in employees[bossId])
        {
            TreeNode tn = (TreeNode)e;
            nodes.Add(tn);
            PopulateTreeView(employees, e.Id, tn.Nodes);
        }
    }
    

    How to use it in your code:

    Dictionary> employees = new Dictionary>();
    
    /* Here you will do the actual reading from DB */
    //             id,        name,      bossId
    employees.Add(666, "The Master     ", 0);
    employees.Add(123, "The Underling 1", 666);
    employees.Add(879, "The Underling 2", 666);
    employees.Add(001, "The Slave 1    ", 123);
    
    this.treeView1.BeginUpdate();
    PopulateTreeView(employees, 0, this.treeView1.Nodes);
    this.treeView1.EndUpdate();
    

    Using the BeginUpdate / EndUpdate methods will eliminate the "blinking" of your GUI.

提交回复
热议问题