protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GenerateTreeView();
}
}
The method below will do a select from your table - creating a relation between ID (which I assume is the treeviews "MAIN PARENT" node) and the "Parent_ID" (which I assume is the child node). It will then create the parent node and subsequently for each child populate the parent node with the method RecursivelyPopulate
private void GenerateTreeView()
{
SqlConnection con = new SqlConnection("CONN STR");
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM MY TABLE", con);
DataSet ds = new DataSet();
adapter.Fill(ds);
ds.Relations.Add("NodeRelation",
ds.Tables[0].Columns["ID"],
ds.Tables[0].Columns["ParentID"]);
foreach (DataRow dbRow in ds.Tables[0].Rows)
{
if (dbRow.IsNull("PARENTID"))
{
RadTreeNode node = CreateNode(dbRow["Description"].ToString(), true);
RadTreeView1.Nodes.Add(node);
RecursivelyPopulate(dbRow, node);
}
}
}
The method below (RecursivelyPopulate
) will for each child in the relation create a child node for the parent created in the method above (GenerateTreeView
)
private void RecursivelyPopulate(DataRow dbRow, RadTreeNode node)
{
foreach (DataRow childRow in dbRow.GetChildRows("NodeRelation"))
{
RadTreeNode childNode = CreateNode(childRow["Description"].ToString();
node.Nodes.Add(childNode);
RecursivelyPopulate(childRow, childNode);
}
}
** Depending on your table structure you can have an Indefinite amount of Parent-Child relations by using the above code snippet