Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

A simple generic TreeList

0.00/5 (No votes)
18 Aug 2010 1  
Convert a generic list of (recursive) objects into a simple hierarchical TreeList


Description


An easy way to convert a generic list into a hierarchical treelist.



Using the code


C#
//A list of nested categories
List<Category> items = getItems();
TreeView<Category> tv = items.ToTreeView(
	c => c.Id, //Primary key
	c => c.ParentId //Foreign key
);
TreeControl1.SetDataSource(
	tv, //Items
	c => c.Title, //DisplayMember
	c => "javascript:alert('" + c.Title + " (id: " + c.Id.ToString() + ")');" //ValueMember
);


C#
//A list of nested directories
TreeList<string> tree = getFolderTree(foldername);
TreeControl2.SetDataSource(
	tree, //Items
	s => s.Substring(s.LastIndexOf("\\") + 1), //DisplayMember
	s => "javascript:alert('" + Server.HtmlEncode(s).Replace(@"\", @"\\") + "');" //ValueMember
);

private TreeList<string> getFolderTree(string folder) {
	string[] folders = Directory.GetDirectories(folder);
	TreeList<string> tree = new TreeList<string>();
	foreach (string dir in folders) {
		tree.Add(dir, folder);
		tree.AddRange(getFolderTree(dir));
	}
	return tree;
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here