我有一个数据层次结构,目前在树形视图中显示。我想知道将此层次结构转换为下拉列表的最简单方法是什么。在树形视图中,我可以找到特定节点并在该节点下添加项。但我不确定如何在下拉列表中实现这一点。以下是我目前拥有的下拉列表代码:
下拉层次结构
**已解决
public void DropDownTree(DropDownList ddl)
{
ddl.Items.Clear();
using (SqlConnection connection = new SqlConnection())
{
// Data Connection
connection.ConnectionString = (ConfigurationManager.ConnectionStrings["AssetWhereConnectionString"].ConnectionString);
connection.Open();
string getLocations = @"
With hierarchy (id, [location id], name, depth, [path])
As (
Select ID, [LocationID], Name, 1 As depth,
Cast(Null as varChar(max)) As [path]
From dbo.Locations
Where ID = [LocationID]
Union All
Select child.id, child.[LocationID], child.name,
parent.depth + 1 As depth,
IsNull(
Cast(parent.id As varChar(max)),
Cast(parent.id As varChar(max))
) As [path]
From dbo.Locations As child
Inner Join hierarchy As parent
On child.[LocationID] = parent.ID
Where child.ID != parent.[Location ID])
Select *
From hierarchy
Order By [depth] Asc";
using (SqlCommand cmd = new SqlCommand(getLocations, connection))
{
cmd.CommandType = CommandType.Text;
using (SqlDataReader rs = cmd.ExecuteReader())
{
while (rs.Read())
{
string id = rs.GetGuid(0).ToString();
int depth = rs.GetInt32(3);
string text = rs.GetString(2);
string locationID = rs.GetGuid(1).ToString();
string padding = String.Concat(Enumerable.Repeat("- ", 2 * depth));
if (id == locationID)
{
ddl.Items.Add(new ListItem(padding + text, id));
}
else
{
int index = ddl.Items.IndexOf(ddl.Items.FindByValue(rs.GetString(4).ToString().ToLower()));
// Fix the location where the item is inserted.
index = index + 1;
ddl.Items.Insert(index, new ListItem(padding + text, id));
}
}
}
}
}
}