I have a datatable loaded from a table of a database that contains elements to be loaded into a treeView.
The database table looks like the following :
+--------+---------+-------------------------------+
|liv | cod | des |
|--------+---------+-------------------------------+
| 1 | AAA | PANE E SOSTITUTIVI |
| 2 | AAAA |GRISSINI - CRACKERS E SIMIL |
| 3 | AAAA | MAIS |
| 4 | AAAA B | BIANCO |
| 4 | AAAA I | INTEGRALE |
| 3 | AAAAA | AVENA |
| 4 | AAAAAB | BIANCO |
| 4 | AAAAAI | INTEGRALE |
| 3 | AAAAB | ALTRO |
| 4 | AAAABB | BIANCO |
| 4 | AAAABI | INTEGRALE |
| 3 | AAAAF | FARRO |
| 4 | AAAAFB | BIANCO |
| 4 | AAAAFI | INTEGRALE |
| 3 | AAAAK | KAMUT |
| 4 | AAAAKB | BIANCO |
| 4 | AAAAKI | INTEGRALE |
| 3 | AAAAR | FRUMENTO |
| 4 | AAAARB | BIANCO |
| 4 | AAAARI | INTEGRALE |
| 3 | AAAAS | RISO |
| 4 | AAAASB | BIANCO |
| 4 | AAAASI | INTEGRALE |
| 2 | AAAC | ESTRUSI |
| 3 | AAACA | MAIS |
+--------+---------+-------------------------------+
Since the maximum level (liv) of the tree is 5, here it is the function that I’m using at the moment to load the datatable into the TreeView :
public void loadFromDataTable(DataTable table, TreeView tree) {
DataView view1 = new DataView(table);
view1.RowFilter = "liv = 1";
foreach (DataRowView dr in view1) {
TreeNode root = new TreeNode(dr["des"].ToString());
DataView view2 = new DataView(table);
view2.RowFilter = "liv = 2 AND cod LIKE '" + dr["cod"].ToString().Trim() + "%'";
foreach (DataRowView dr2 in view2) {
TreeNode root2 = new TreeNode(dr2["des"].ToString());
DataView view3 = new DataView(table);
view3.RowFilter = "liv = 3 AND cod LIKE '" + dr2["cod"].ToString().Trim() + "%'";
foreach (DataRowView dr3 in view3) {
TreeNode root3 = new TreeNode(dr3["des"].ToString());
DataView view4 = new DataView(table);
view4.RowFilter = "liv = 4 AND cod LIKE '" + dr3["cod"].ToString().Trim() + "%'";
foreach (DataRowView dr4 in view4) {
TreeNode root4 = new TreeNode(dr4["des"].ToString());
DataView view5 = new DataView(table);
view5.RowFilter = "liv = 5 AND cod LIKE '" + dr4["cod"].ToString().Trim() + "%'";
foreach (DataRowView dr5 in view5) {
TreeNode root5 = new TreeNode(dr5["des"].ToString());
root4.Nodes.Add(root5);
}
root3.Nodes.Add(root4);
}
root2.Nodes.Add(root3);
}
root.Nodes.Add(root2);
}
tree.Nodes.Add(root);
}
I was wondering if there is a better approach to avoid the use of these five nested loops . Any object oriented approach ?
Thanks for the help.
You can use recursion for adding nodes:
And usage is very simple:
Also this code will work for variable tree depth – it goes deeper only if nodes found on current level. BTW if datatable is large, then consider to do lazy loading of child nodes. In this case you also can use method above, but without recursive call.