Associate an ASP.NET TreeView Control with a Dataset

On MSDN, they talk about the TreeView control (the "data binding" item):

A TreeView control can also be bound to an XmlDocument object or a DataSet with relationships . To bind to one of these data sources, set the DataSource property of the TreeView control to source data, and then call the DataBind method.

So, on a simple WebForms page with only TreeView, I wrote:

DataSet ds = new DataSet(); DataTable dt = new DataTable("Masters"); ds.Tables.Add(dt); dt.Columns.Add("MasterId", typeof(Int32)); dt.Columns.Add("Name", typeof(String)); DataTable dt1 = new DataTable("Details"); ds.Tables.Add(dt1); dt1.Columns.Add("DetailId", typeof(Int32)); dt1.Columns.Add("MasterId", typeof(Int32)); dt1.Columns.Add("Name", typeof(String)); DataRow rw; DataRow rw1; for (int i = 0; i < 5; i++) { rw=dt.NewRow(); dt.Rows.Add(rw); rw["MasterId"] = i; rw["Name"] = "Master Name " + i.ToString(); for (int j = 0; j < 10; j++) { rw1 = dt1.NewRow(); dt1.Rows.Add(rw1); rw1["DetailId"] = i * 5 + j; rw1["MasterId"] = i; rw1["Name"] = "Detail Name " + j.ToString() + " of Master Name "+ i.ToString(); } } ds.Relations.Add(new DataRelation("Masters_Details",dt.Columns["MasterId"], dt1.Columns["MasterId"])); TreeView1.DataSource = ds; TreeView1.DataBind(); 

But in the line where I set the DataSource, it throws an exception:

HierarchicalDataBoundControl accepts only data sources that implement IHierarchicalDataSource or IHierarchicalEnumerable.

I realized that this is happening because the DataSet does not implement such an interface ... so why do they write, can I associate with a "DataSet with relations"? Thank you in advance

+7
source share
1 answer

This code shows how to move from a hierarchical table to a TreeView. There is nothing complicated here, but you need to do a few tricks to make it work.

The first trick is to sort the entries using the ParentID. We cannot insert a node into the tree until its parent node is in the tree. This implies a special case where the root of the tree node must be inserted first, since it does not have a parent.

Here is an example of data:

 // Create the DataTable and columns DataTable ItemTable = new DataTable("MyTable"); ItemTable.Columns.Add("ID" , typeof(int )); ItemTable.Columns.Add("ParentID", typeof(int )); ItemTable.Columns.Add("Name" , typeof(String)); // add some test data ItemTable.Rows.Add(new object[] { 0,-1, "Bill Gates" }); ItemTable.Rows.Add(new object[] { 1, 0, "Steve Ballmer" }); ItemTable.Rows.Add(new object[] { 3, 1, "Mary Smith" }); ItemTable.Rows.Add(new object[] { 2, 0, "Paul Allen" }); ItemTable.Rows.Add(new object[] { 4, 2, "Ahmed Jones" }); ItemTable.Rows.Add(new object[] { 5, 2, "Wing Lee" }); // Use the Select method to sort the rows by ParentID DataRow[] SortedRows; SortedRows = ItemTable.Select("", "ParentID"); 

Hope you find this helpful

0
source

All Articles