I am having issues trying to build a treeview using asp.net and c#.
My outcome is trying to show a treeview like this (sorry for wrong spellings or wrong location but this is just test data):
UK
-> London
-> SouthEast
->Kent
->Essex
-> NorthEast
->Cambridge
Wales
-> Cardiff
Here is my code below:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1"
ValidateRequest="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:TreeView ID="TreeView1" runat="server" >
</asp:TreeView>
</form>
</body>
</html>
C# :
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Collections.ObjectModel;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
public class ViewModel
{
public string LocationName { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
ICollection<ViewModel> list = new Collection<ViewModel>();
list.Add(new ViewModel { LocationName = "UK" });
list.Add(new ViewModel { LocationName = "UK.London.SouthEast.Kent" });
list.Add(new ViewModel { LocationName = "UK.London.SouthEast.Essex" });
list.Add(new ViewModel { LocationName = "Wales.Cardiff" });
list.Add(new ViewModel { LocationName = "Wales" });
list.Add(new ViewModel { LocationName = "UK.London.NorthEast.Cambridge" });
PopulateTreeview(list);
}
private void PopulateTreeview(ICollection<ViewModel> listOfCities)
{
foreach (ViewModel vm in listOfCities)
{
TreeNode tnNode = new TreeNode();
tnNode.Text = vm.LocationName;
tnNode.Value = vm.LocationName;
tnNode.Expanded = true;
TreeView1.Nodes.Add(tnNode);
}
}
}
}
As you can see my test data is this format "UK.London.SouthEast.Essex". I will get this data from DB. I need to build a parent node and child nodes using this data but dont know how to? Been trying for few days to write how to do this.