I'm trying to populate treeview with list od items. Item contain name and path:
Here is the code:
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);
}
}
Populate list and create tree:
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; }
}
This works fine but instead of last number of path I want to show name. How to do that?
Your function did everything right, but it needed little modification. I've replaced:
foreach (TreeNode item in nodeList)
{
if (item.Text == f)
{
node = item;
}
}
to
foreach (TreeNode item in nodeList)
{
if (item.Tag.ToString() == f)
{
node = item;
}
}
and
if (node == null)
{
node = new TreeNode(f);
nodeList.Add(node);
}
to
if (node == null)
{
node = new TreeNode(name);
node.Tag = f;
nodeList.Add(node);
}
I hope it helps :)