C# Asp.NET下拉列表以树的形式从列表中添加列表项
我有一个方法,我必须从一个像树一样的集合中填充dropdownlist。我有父对象列表,每个父对象都有子对象列表,每个子对象都有孙子对象列表等等。 我必须循环遍历该集合,因为我想缩进项以便构建层次结构 ddl应该如下所示:(-是缩进的符号) 父母亲 -孩子 --孙子 ---外孙 -孩子 父母亲 ……等等 我应该如何改变这个方法,这样我就不会在循环中有循环在循环中,因为我不知道树的深度 提前谢谢 方法:C# Asp.NET下拉列表以树的形式从列表中添加列表项,c#,asp.net,webforms,C#,Asp.net,Webforms,我有一个方法,我必须从一个像树一样的集合中填充dropdownlist。我有父对象列表,每个父对象都有子对象列表,每个子对象都有孙子对象列表等等。 我必须循环遍历该集合,因为我想缩进项以便构建层次结构 ddl应该如下所示:(-是缩进的符号) 父母亲 -孩子 --孙子 ---外孙 -孩子 父母亲 ……等等 我应该如何改变这个方法,这样我就不会在循环中有循环在循环中,因为我不知道树的深度 提前谢谢 方法: private void BindObjectDropDown() {
private void BindObjectDropDown()
{
ddlObject.Items.Clear();
ObjectCollection collection = Object.GetList();
if (collection != null && collection.Count > 0)
{
foreach (var parent in collection)
{
ddlObject.Items.Add(new ListItem($"{parent.Title}", parent.Id.ToString()));
if (parent.Objects != null && parent.Objects.Count > 0)
{
foreach (var child in parent.Objects)
{
ddlObject.Items.Add(new ListItem($"{_ddlIndent}{child.Title}", child.Id.ToString()));
if (child.Objects != null && child.Objects.Count > 0)
{
foreach (var grandchild in child.Objects)
{
ddlObject.Items.Add(new ListItem($"{_ddlIndent}{_ddlIndent}{grandchild.Title}", grandchild.Id.ToString()));
//and so on and so on ....
}
}
}
}
}
foreach (ListItem item in ddlObject.Items)
{
item.Text = HttpUtility.HtmlDecode(item.Text);
}
}
}
如果有人想要一个解决方案,递归,当然:
private void BindMyObjectDropDown()
{
ddlMyObject.Items.Clear();
MyObjectCollection collection = MyObject.GetList(0, true);
if (collection != null && collection.Count > 0)
{
AddDdlItems(collection, 0);
foreach (ListItem item in ddlMyObject.Items)
{
item.Text = HttpUtility.HtmlDecode(item.Text);
}
}
ddlMyObject.Items.Insert(0, new ListItem(EntityResource.DefaultDropDownPick, "0"));
}
private void AddDdlItems(MyObjectCollection collection, int depth)
{
string indent = string.Empty;
for (int i = 0; i < depth; i++)
{
indent += _ddlIndent;
}
foreach (var myObject in collection)
{
ddlMyObject.Items.Add(new ListItem($"{indent}{myObject.Title}", myObject.Id.ToString()));
if (myObject.Objects!= null && myObject.Objects.Count > 0)
{
AddDdlItems(myObject.Objects, depth + 1);
}
}
}
private void bindMyObject下拉列表()
{
ddlMyObject.Items.Clear();
MyObjectCollection=MyObject.GetList(0,true);
if(collection!=null&&collection.Count>0)
{
AddDdlItems(集合,0);
foreach(ddlMyObject.Items中的ListItem项)
{
item.Text=HttpUtility.HtmlDecode(item.Text);
}
}
插入(0,新列表项(EntityResource.DefaultDropDownPick,“0”);
}
私有void AddDdlItems(MyObjectCollection集合,int depth)
{
字符串缩进=string.Empty;
for(int i=0;i0)
{
AddDdlItems(myObject.Objects,深度+1);
}
}
}