Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Try the following code in your aspx or ascx file:</p> <pre><code>&lt;asp:Treeview ID="TreeView1" runat="server" /&gt; </code></pre> <p>And in the codebehind to populate it:</p> <pre><code>private void PopulateTreeView() { DataSet ds = new DataSet(); //(populate the dataset with the table) //Use LINQ to filter out items without a parent DataTable parents = ds.Tables[0].AsEnumerable() .Where(i =&gt; i.Field&lt;object&gt;("parentid") == DBNull.Value) .CopyToDataTable(); //Use LINQ to filter out items with parent DataTable children = ds.Tables[0].AsEnumerable() .Where(i =&gt; i.Field&lt;object&gt;("parentid") != DBNull.Value) .OrderBy(i =&gt; i.Field&lt;int&gt;("parentid")) .CopyToDataTable(); //Add the parents to the treeview foreach(DataRow dr in parents) { TreeNode node = new TreeNode(); node.Text = dr["name"].ToString(); node.Value = dr["id"].ToString(); TreeView1.Nodes.Add(node); } //Add the children to the parents foreach(DataRow dr in children) { TreeNode node = new TreeNode(); node.Text = dr["name"].ToString(); node.Value = dr["id"].ToString(); TreeNode parentNode = FindNodeByValue(dr["parentid"].ToString()); if(parentNode != null) parentNode.ChildNodes.Add(node); } } private TreeNode FindNodeByValue(string value) { foreach(TreeNode node in TreeView1.Nodes) { if(node.Value = value) return node; TreeNode pnode = FindNodeRecursion(node, value); if(pnode != null) return pnode; } return null; } private TreeNode FindNodeRecursion(TreeNode parentNode, string value) { foreach(TreeNode node in parentNode.ChildNodes) { if(node.Value = value) return node; TreeNode pnode = FindNodeRecursion(node, value); if(pnode != null) return pnode; } return null; } </code></pre> <p>There might be a better way to do this and I haven't tested it, but it should work. Or you could always try out <a href="http://demos.telerik.com/aspnet-ajax/treeview/examples/overview/defaultcs.aspx" rel="nofollow">Telerik</a> or another third party tool that makes data binding for these types of controls super easy.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload