[英]Populate treeview with - path enumeration
我正在嘗試使用列表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; }
}
這工作正常,但不是我要顯示名稱的路徑的最后一個數字。 怎么做?
您的函數可以正確執行所有操作,但幾乎不需要修改。 我已替換:
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);
}
希望對您有所幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.