I have a WinForm TreeView Control that displays the Parent Child relationship of CaseNotes(I know that means nothing to most of you but it helps me visualize the answers).
I've created much simplier extension method for TreeView, involving use of new simple extending class that adds two useful properties to TreeNode.
internal class IdNode : TreeNode
{
public object Id { get; set; }
public object ParentId { get; set; }
}
public static void PopulateNodes(this TreeView treeView1, DataTable dataTable, string name, string id, string parentId)
{
treeView1.BeginUpdate();
foreach (DataRow row in dataTable.Rows)
{
treeView1.Nodes.Add(new IdNode() { Name = row[name].ToString(), Text = row[name].ToString(), Id = row[id], ParentId = row[parentId], Tag = row });
}
foreach (IdNode idnode in GetAllNodes(treeView1).OfType())
{
foreach (IdNode newparent in GetAllNodes(treeView1).OfType())
{
if (newparent.Id.Equals(idnode.ParentId))
{
treeView1.Nodes.Remove(idnode);
newparent.Nodes.Add(idnode);
break;
}
}
}
treeView1.EndUpdate();
}
public static List GetAllNodes(this TreeView tv)
{
List result = new List();
foreach (TreeNode child in tv.Nodes)
{
result.AddRange(GetAllNodes(child));
}
return result;
}
public static List GetAllNodes(this TreeNode tn)
{
List result = new List();
result.Add(tn);
foreach (TreeNode child in tn.Nodes)
{
result.AddRange(GetAllNodes(child));
}
return result;
}
Thanks to the modiX for his methods to get all (nested) nodes.