Just Code‎ > ‎

C# - Create Tree structured TreeNodes data from sql rows. Use with TreeView in winforms

posted Feb 14, 2010, 4:10 AM by Peter Henell
public TreeNode GetPortfolioTree(string date)
{
System.Data.SqlClient.SqlDataReader reader
= DataAccess.PortfolioTreeAccess.GetPortfolioTreeReader(date);
TreeNode rootNode
= CreateNode(reader);
return CreateTree(reader, rootNode, rootNode, (int)reader["Level"]);
}

/// <summary>
///
/// </summary>
/// <param name="reader">SQLDataReader to read from</param>
/// <param name="targetNode">Node to where we will put childnodes</param>
/// <param name="prevNode">node that where created the previous lap</param>
/// <param name="prevLevel">level of previouse node</param>
/// <returns>A node with tree structured children</returns>
private TreeNode CreateTree(SqlDataReader reader, TreeNode targetNode, TreeNode prevNode, int prevLevel)
{
// L?gg till alla p? nuvarande niv?,
// om niv? g?r upp -> anropa f?r ny niv?
// om den g?r ner -> returnera resultat
if (reader.Read())
{
if (prevLevel == (int)reader["Level"])
{
// L?gg till childs till targetNode, dvs samma niv? som f?reg?ende
TreeNode newChild = CreateNode(reader);
targetNode.ChildNodes.Add(newChild);
CreateTree(reader, targetNode, newChild, prevLevel);
}
else if ((int)reader["Level"] > prevLevel)
{
// L?gg till childs till f?reg?ende noden
TreeNode newLevelNode = CreateNode(reader);
prevNode.ChildNodes.Add(newLevelNode);
CreateTree(reader, prevNode, newLevelNode, (
int)reader["Level"]);
}
else if ((int)reader["Level"] < prevLevel)
{
// L?gg till noden till
// G? bak?t i tr?det x steg. D?r x = skillnaden mellan prevLevel och nya leveln
int stepToTakeBackwards = prevLevel - (int)reader["Level"];
TreeNode newMother
= targetNode;

for (int i = 0; i < stepToTakeBackwards; i++)
{
newMother
= newMother.Parent;
}
TreeNode newChild
= CreateNode(reader);
newMother.ChildNodes.Add(newChild);
CreateTree(reader, newMother, newChild, (
int)reader["Level"]);
}

}
return targetNode;
}

private static TreeNode CreateNode(SqlDataReader reader)
{
return new TreeNode(string.Format("{0}_{1}", reader["NodeShortName"].ToString(), reader["Level"].ToString()));
}
Comments