我有一个当前显示在 TreeView 中的数据层次结构。我想知道将此层次结构也转换为下拉列表的最简单方法是什么。在 TreeView 中,我可以找到一个特定的节点并在该节点下添加一个项目。我不确定如何使用下拉列表来做到这一点。下面是我到目前为止的下拉菜单代码:
下拉层次结构
**已解决
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));
}
}
}
}
}
}
最佳答案
你的代码看起来不错,但从你在问题下的评论来看,这行的索引听起来像是负值:
int index = ddl.Items.IndexOf(ddl.Items.FindByValue(rs.GetString(4).ToString().ToLower()));
负值表示未找到您正在搜索的下拉列表项。如果下拉列表为空,情况肯定会如此。您将搜索不存在的项目。
下面是对您的代码的更新,它将产生以下内容(我相信这就是您正在寻找的内容):
尝试将您的代码更改为以下内容:
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()));
//Check to see if this item exists before trying to insert
if (index == -1)
{
//Add the item if it doesn't exist
ddl.Items.Add(new ListItem(padding + text, id));
}
else
{
ddl.Items.Insert(index, new ListItem(padding + text, id));
}
}
关于c# - 在下拉列表中显示层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6252061/