I need to create a menu structure taken from a database table that uses the identifier and ParentID and the ranking that is used to determine the order of nodes.
Root(ID 1, ParentID 0, Rank 1)
- Node(ID 2, ParentID 1, Rank 1)
- Node(ID 3, ParentID 2, Rank 1)
- Node(ID 4, ParentID 3, Rank 1)
- Node(ID 5, ParentID 3, Rank 2)
- Node(ID 6, ParentID 2, Rank 2)
- Node(ID 7, ParentID 2, Rank 3)
- Node(ID 8, ParentID 1, Rank 2)
- Node(ID 9, ParentID 8, Rank 1)
- Node(ID 10, ParentID 8, Rank 2)
I tried to create a function to iterate the SQL data and create this tree structure, but I'm not sure how to handle the depth of the add. I can add the first level of nodes by simply checking to see if they have a ParentID, I can add a second level of nodes to the else condition, however I'm not sure how to add the following hierarchy levels.
Iterating through the database:
using (var command = new SqlCommand(_Query, _Connection))
{
_Connection.Open();
var _Reader = command.ExecuteReader();
while (_Reader.Read())
{
CreateNode((int)_Reader["MenuID"], (int)_Reader["ParentID"], (int)_Reader["Rank"], _Reader["English"].ToString());
}
_Connection.Close();
}
Creating Nodes:
private void CreateNode(int id, int parentID, int rank, string text)
{
if(parentID == -1)
{
TreeNode _Node = new TreeNode(text, id.ToString());
Root.Nodes.Add(_Node);
}
if (parentID != -1)
{
foreach (TreeNode _Node in Root.Nodes)
{
if (_Node.Value == parentID.ToString())
{
_Node.ChildNodes.Add(new TreeNode(text, id.ToString()) { ShowCheckBox = true } );
}
}
}
}
This is currently not sorting nodes by rank
I expect the HTML output to be similar to the following:
<ul id="1">
<li>A</li>
<li>
<ul id="2">
<li>B</li>
<li>
<ul id="3">
<li>C</li>
<li>
<ul id="4">
<li>D</li>
</ul>
</li>
<li>
<ul id="5">
<li>E</li>
</ul>
</li>
</ul>
</li>
<li>
<ul id="6">
<li>F</li>
</ul>
</li>
<li>
<ul id="7">
<li>G</li>
</ul>
</li>
</ul>
</li>
<li>
<ul id="8">
<li>H</li>
<ul>
<li>
<ul id="9">
<li>I</li>
</ul>
</li>
<li>
<ul id="10">
<li>J</li>
</ul>
</li>
</ul>
</ul>
</li>
</ul>
http://jsfiddle.net/RjE7H/