3

我有一个带有名为“类别”的表的数据库。该表有 3 列:1. ID 2. Name 3. ParentID。

id | Name    |ParentID
_____________________
1  | John    | 0
2  | Charlie | 1
3  | Vasily  | 1
4  | David   | 2
5  | Edward  | 3

所以约翰是查理和瓦西里的父母,大卫是查理的孩子,爱德华是瓦西里的孩子。问题是:考虑到子面板必须位于其父面板内,我如何为每个类别创建和填充一些面板?这个问题与这里的问题几乎相同,但是我真的需要它与面板而不是树视图一起使用。谢谢你。

4

1 回答 1

2

you should change the code as it is

public class MyObject
{
    public int Id;
    public int ParentId;
    public string Name;
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack) {
        List<MyObject> list = new List<MyObject>();
        list.Add(new MyObject() { Id = 1, Name = "Alice", ParentId = 0 });
        list.Add(new MyObject() { Id = 2, Name = "Bob", ParentId = 1 });
        list.Add(new MyObject() { Id = 3, Name = "Charlie", ParentId = 1 });
        list.Add(new MyObject() { Id = 4, Name = "David", ParentId = 2 });

        BindTree(list, null);
    }
}

private void BindTree(IEnumerable<MyObject> list, Panel parentPanel)
{

    var nodes = list.Where(x => parentPanel == null ? x.ParentId == 0 : x.ParentId == int.Parse(parentPanel.ID));
    foreach (var node in nodes) {
        Panel newPanel = new Panel() { ID = node.Id.ToString() };
        if (parentPanel == null) {
            Panel1.Controls.Add(newPanel);
        } else {
            parentPanel.Controls.Add(newPanel);
        }
        BindTree(list, newPanel);
    }
}
于 2012-11-17T23:36:15.543 回答