Cameron Kloot

I am trying to load names of files into a treeview:

foreach (object file in Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\My Debate"))
foreach (object directory in Directory.GetDirectories(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\My Debate"))

// int a = evFilesTV.Nodes.IndexOfKey(Path.GetFileNameWithoutExtension(directory.ToString()));

// foreach (object file2 in Directory.GetFiles(directory.ToString()))
// {
// evFilesTV.Nodes[Angel].Nodes.Add(Path.GetFileNameWithoutExtension(file2.ToString()));
// }

the rest works fine, but when i get down to the IndexOfKey method it starts to go wrong. when i run a messagebox showing the selected node's index, it ran 1 (there is only one folder i am loading); but when i use the IndexOfKey method, it returns -1. Thus, the second blue line runs the index out of range exception.
Any help

PS it has that smile thing where there should be an "a". Sad

Re: Visual C# Express Edition Treeview exception


The problem is that when you add the nodes, like this:

treeView.Nodes.Add(string text)

you are only specifying the text for the node and not the key. So when you later look for the index of the key, it can't find it.

To fix it, you need to use the form:

treeView.Nodes.Add(string key, string text);

or specifically for your code do this:

string d = Path.GetFileNameWithoutExtension(directory.ToString());


int a = evFilesTV.Nodes.IndexOfKey(d);

Re: Visual C# Express Edition Treeview exception

Sven De Bont

The Nodes.Add() method returns a reference to the added TreeNode object. You should use this instead of trying to get a reference using IndexOfKey.

TreeNode node = evFilesTV.Nodes.Add(directory.ToString());

foreach(object file2 in DirectoryGetFiles(directory.ToString())




The reason you cannot use IndexOfKey() is because you have added to Node to the Treeview without specifiyng a Key. If you do want to use IndexOfKey (which I discourage), add the Noded to the Treeview by using the Add(string key, string text) overload:

TreeNode node = evFilesTV.Nodes.Add(directory.ToString(), directory.ToString());

-> the first parameter is the key, the second is the the text that should be displayed in the Treeview.

Hope this helps,

Re: Visual C# Express Edition Treeview exception

Cameron Kloot

Oh! of course.
Thank you.