In a form I have a treeview (tvArbol). The same, complete it with all the directories and files of Windows. To do this, every time I expand a node, I obtain and complete the treeview with the nodes "children" of the expanded node.
All nodes have a checkbox. When I checkbox a node, all checkboxes "children" of this one are marked.
The problem I have is that if the "parent" node has not yet been expanded (therefore, the "children" nodes were not loaded) the function to check the "children" checkbox obviously only marks the "parent" checkbox.
I tried calling one function inside another but I am generated loops or something does not work because the application is "marked".
Maybe it's something very simple, but I do not see how to do it.
I put the code of what I have done and working so far:
private void Form1_Load(object sender, EventArgs e)
{
foreach (DriveInfo unidad in DriveInfo.GetDrives())
{
TreeNode raiz = new TreeNode(unidad.Name);
raiz.Tag = unidad.Name;
raiz.ImageIndex = 0;
raiz.Nodes.Add(new TreeNode());
tvArbol.Nodes.Add(raiz);
}
}
private void tvArbol_BeforeExpand(object sender, TreeViewCancelEventArgs e)
{
if (e.Node.Tag != null)
{
CompletarArbolConDirectoriosYArchivos(e.Node, (string)e.Node.Tag);
}
}
private void CompletarArbolConDirectoriosYArchivos(TreeNode nodo, string path)
{
nodo.Nodes.Clear();
try
{
DirectoryInfo directorioPadre = new DirectoryInfo(path);
DirectoryInfo[] subDirectorios = directorioPadre.GetDirectories();
foreach (DirectoryInfo subDirectorio in subDirectorios)
{
TreeNode directorioHijo = new TreeNode(subDirectorio.Name);
directorioHijo.Tag = subDirectorio.FullName;
directorioHijo.ImageIndex = 1;
directorioHijo.Nodes.Add(new TreeNode());
nodo.Nodes.Add(directorioHijo);
}
List<FileInfo> archivos = new List<FileInfo>();
archivos.AddRange(directorioPadre.GetFiles());
foreach (FileInfo archivo in archivos)
{
TreeNode archivoHijo = new TreeNode(archivo.Name);
archivoHijo.ImageIndex = 2;
archivoHijo.Tag = archivo;
nodo.Nodes.Add(archivoHijo);
}
}
catch
{
// TODO: completar ...
}
finally
{
nodo.Tag = null;
}
}
private void tvArbol_AfterCheck(object sender, TreeViewEventArgs e)
{
bool enProceso = false;
if (enProceso) return;
enProceso = true;
try
{
MarcarNodos(e.Node, e.Node.Checked);
}
finally
{
enProceso = false;
}
}
private void MarcarNodos(TreeNode nodo, bool marca)
{
foreach (TreeNode nodoHijo in nodo.Nodes)
{
nodoHijo.Checked = marca;
MarcarNodos(nodoHijo, marca);
}
}
A reference image: