Nikolay
Nikolay

Reputation: 161

Update Treeview with new filepath

I have an Observable collection of Paths. The thing I want to do is to update my treeView on collection changed. Could you please help me with creating method that takes Treeview, FilePath and PathSeparator as parameters and adding new node to my treeView. This is what i have now:

private void MyCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    TreeViewAddNode(TreeView,Path,PathSeparator)
}

TreeViewAddNode(TreeView treeView, string path, char pathSeparator)
{
    foreach (string subPath in path.Split(pathSeparator)) 
    { 
        //Hear should be logic to add new nodes if they don't exist }
    }
}

As the Result I wanna have something like that:
C:
--Temp
----File1.txt
----File2.txt
----New Foledr
-------File3.txt
--AnotherFolder
----File4.txt
D:
--New Folder
----File.txt

Upvotes: 0

Views: 503

Answers (1)

Huntt
Huntt

Reputation: 185

EDIT

Now with better understanding on what is being asked:

private void TreeViewAddNode(TreeView treeView, string path, char pathSeparator)
{
    string[] split = path.Split(pathSeparator);

    for(int i = 0; i < split.Length; i++)
    {
        if(i == 0)
        {
            checkTreeView(treeView, split[0]);
        }
        else
        {
            TreeNode node = treeView1.Nodes.Find(split[i - 1], true)[0];
            checkNodes(node, split[i]);                                        
        }
     }                   
 }

private void checkTreeView(TreeView treeView, string path)
{
    bool exists = false;

    foreach(TreeNode node in treeView.Nodes)
    {
        if(node.Text == path)
        {
            exists = true;
        }
    }

    if(!exists)
    {
        TreeNode node = treeView.Nodes.Add(path);
        node.Name = path;
    }
}

private void checkNodes(TreeNode parent, string path)
{
    bool exists = false;

    foreach(TreeNode node in parent.Nodes)
    {
        if(node.Text == path)
        {
            exists = true;
        }                
    }

    if(!exists)
    {
        TreeNode node = parent.Nodes.Add(path);
        node.Name = path;
    }
}

checkTreeView checks if the path is allready present in the treeview nodes. if it isn't add it to the treeview. Same goes for checkNodes.

Upvotes: 1

Related Questions