I tried to bind data from few tables in db to TreeView.
Beleow is my solution.
ASP TreeView can be bound only to XmlDataSource or SiteMapDataSource, so I had to build XmlDataSource dynamically.
Listing 1.
Function building XmlDataSource
public XmlDataSource GenerateDataSource(List<products1> custList)
{
XmlDataSource returnItems = new XmlDataSource();
returnItems.EnableCaching = false;
XDocument document = new XDocument();
using (EntityDataModel edm = new EntityDataModel())
{
XElement customersRoot = new XElement("customers");
foreach (products1 customer in custList)
{
XElement custNode = new XElement("customer", new XAttribute("text", customer.fullname),
new XAttribute("value", customer.name));
var magazines = edm.prod.Where(p => p.name == customer.name)
.SelectMany(p => p.magz);
foreach (var magazine in magazines)
{
// Create Magazine node
XElement magazineNode = new XElement("magazine", new XAttribute("text", magazine.name),
new XAttribute("value", magazine.id));
var users = edm.prod.Where(p => p.id == mag.id).SelectMany(p => p.users);
foreach (var user in users)
{
// Create User node
XElement userNode = new XElement("user", new XAttribute("text", user.fullname),
new XAttribute("value", user.id));
magazineNode.Add(userNode);
}
custNode.Add(magazineNode);
}
customersRoot.Add(custNode);
}
document.Add(customersRoot);
returnItems.Data = document.ToString();
}
returnItems.XPath = "/*/*";
return returnItems;
}
Listing 2.
Binding to control:
XmlDataSource xmlDataSource = GenerateDataSource(custList);
TreeView1.DataSource = xmlDataSource;
TreeView1.DataBind();
Listing 3.
Setting control to read text and value properties from XmlDataSource.
<asp:TreeView ID="TreeView1" runat="server" ExpandDepth="1"
ShowLines="True" >
<DataBindings>
<asp:TreeNodeBinding DataMember="customer" TextField="text" ValueField="value" SelectAction="None"/>
<asp:TreeNodeBinding DataMember="magazine" TextField="text" ValueField="value" SelectAction="None"/>
<asp:TreeNodeBinding DataMember="user" TextField="text" ValueField="value" SelectAction="None"/>
</DataBindings>
</asp:TreeView>