I'm having a hard time trying to get a Treeview to display child notes.
I have a DataTable which is filled with Data from a query.
The table is something like this.
| ParentOT | ChildOT
-------------------
1 | 2
1 | 3
1 | 4
4 | 5
5 | 6
now, what I need is to order this data in a TreeView.
The result must be something like this (using this same table)
1
|
--2
|
--3
|
--4
|
--5
|
--6
I tried to this on Windows Forms and the only thing I can get is the tree to show only 1 set of childs. like this
1
|
--2
|
--3
|
--4
|
--5
|
5
|
--6
I tried to do it like this:
DataTable arbolSub = mssql_cnn.ejecutarSqlSelect(q2);
//Metodo 2: muestra las ot correctamente pero no muestra mas detalle de subOT.
if (trvOTHs.Nodes.Count > 0)
{
trvOTHs.Nodes.Clear();
}
trvOTHs.BeginUpdate();
if (arb.Rows.Count > 0)
{
string otPadre = arb.Rows[0][0].ToString();
int nivel = 0;
trvOTHs.Nodes.Add(arbolSub.Rows[0]["OT Padre"].ToString());
for (int i = 0; i < arbolSub.Rows.Count; i++)
{
//trvOTHs.Nodes.Add(arbolSub.Rows[0]["OT Padre"].ToString());
if (arbolSub.Rows[i]["OT Padre"].ToString() == otPadre)
{
if (trvOTHs.Nodes[nivel].Text == otPadre)
{
trvOTHs.Nodes[nivel].Nodes.Add(arbolSub.Rows[i]["OT Hija"].ToString());
}
}
else
{
otPadre = arbolSub.Rows[i+1]["OT Padre"].ToString();
TreeNode nodo = new TreeNode(otPadre.ToString());
trvOTHs.Nodes.Add(nodo);
nivel++;
}
}
trvOTHs.Nodes[0].Remove();
trvOTHs.ExpandAll();
}
trvOTHs.EndUpdate();
where trvOTHs is a TreeView.
Please Help! Thanks
EDIT: Thanks for the reply. I finally worked around this,using a idea given by a friend and using something like the suggested solution by @Mohammad abumazen.
I ended up using two methods recursively:
private TreeView cargarOtPadres(TreeView trv, int otPadre, DataTable datos)
{
if (datos.Rows.Count > 0)
{
foreach (DataRow dr in datos.Select("OTPadre='"+ otPadre+"'"))
{
TreeNode nodoPadre = new TreeNode();
nodoPadre.Text = dr["OTPadre"].ToString();
trv.Nodes.Add(nodoPadre);
cargarSubOts(ref nodoPadre, int.Parse(dr["OTHija"].ToString()), datos);
}
}
return trv;
}
private void cargarSubOts(ref TreeNode nodoPadre, int otPadre, DataTable datos)
{
DataRow[] otHijas = datos.Select("OTPadre='" + otPadre +"'");
foreach (DataRow drow in otHijas)
{
TreeNode hija = new TreeNode();
hija.Text = drow["OTHija"].ToString();
nodoPadre.Nodes.Add(hija);
cargarSubOts(ref hija, int.Parse(drow["OTHija"].ToString()), datos);
}
}
This did it. I leave it here in case anyone needs it. Thanks again.
See Question&Answers more detail:
os