我正在尝试使用列表od项填充treeview。项目包含名称和路径:
代码如下:
private void CreateTree(TreeNodeCollection nodeList, string path, string name)
{
TreeNode node = null;
string f = string.Empty;
int p = path.IndexOf('/');
if (p == -1)
{
f = path;
path = "";
}
else
{
f = path.Substring(0, p);
path = path.Substring(p + 1, path.Length - (p + 1));
}
node = null;
foreach (TreeNode item in nodeList)
{
if (item.Text == f)
{
node = item;
}
}
if (node == null)
{
node = new TreeNode(f);
nodeList.Add(node);
}
if (path != "")
{
CreateTree(node.Nodes, path, name);
}
}
填充列表并创建树:
List<Item> list = new List<Item>();
list.Add(new Item { Name = "Parent", Path = "1" });
list.Add(new Item { Name = "daughter", Path = "1/2" });
list.Add(new Item { Name = "son", Path = "1/3" });
list.Add(new Item { Name = "daughter", Path = "1/2/4" });
list.Add(new Item { Name = "daughter", Path = "1/2/5" });
list.Add(new Item { Name = "son", Path = "1/3/6" });
list.Add(new Item { Name = "son", Path = "1/3/7" });
list.Add(new Item { Name = "son", Path = "1/2/5/8" });
list.Add(new Item { Name = "daughter", Path = "1/2/5/9" });
list.Add(new Item { Name = "daughter", Path = "1/3/6/10" });
list.Add(new Item { Name = "son", Path = "1/3/6/11" });
list.Add(new Item { Name = "daughter", Path = "1/3/7/12" });
list.Add(new Item { Name = "daughter", Path = "1/3/7/13" });
list.Add(new Item { Name = "daughter", Path = "1/3/7/14" });
foreach (Item line in list)
{
CreateTree(treeView1.Nodes, line.Path, line.Name);
}
class Item
{
public string Name { get; set; }
public string Path { get; set; }
}
这可以正常工作,但不是我要显示名称的路径的最后一个数字。该怎么做?
答案 0 :(得分:1)
您的函数可以正确执行所有操作,但几乎不需要修改。我已替换:
foreach (TreeNode item in nodeList)
{
if (item.Text == f)
{
node = item;
}
}
到
foreach (TreeNode item in nodeList)
{
if (item.Tag.ToString() == f)
{
node = item;
}
}
和
if (node == null)
{
node = new TreeNode(f);
nodeList.Add(node);
}
到
if (node == null)
{
node = new TreeNode(name);
node.Tag = f;
nodeList.Add(node);
}
我希望这会有所帮助:)