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);
}
}