0

i need help with this piece of code to get files from directory and populate them in treeview.

foreach (DirectoryInfo directory in directories)
{
    TreeNode node = TreeView.Nodes[0].Nodes.Add(directory.Name);
    node.ImageIndex = 1;


    foreach (FileInfo file in directory.GetFiles())
    {
        if (file.Exists)
        {
            TreeNode nodes = TreeView.Nodes[0].Nodes(node.Index).Nodes.Add(file.Name);
            nodes.ImageIndex = 2;
        }
    }
}

i get this error: An object reference is required for the non-static field, method, or property 'System.Windows.Forms.TreeView.Nodes.get'

i appreciate any kind of help thanks

4

2 回答 2

3

TreeView不是静态类,这就是您收到该错误消息的原因。您应该将您习惯使用的位置更改TreeView为实例的实际名称。

例如:

TreeNode node = TreeView.Nodes[0].Nodes.Add(directory.Name);

应该

//myTreeView is the name of my TreeView object
TreeNode node = myTreeView.Nodes[0].Nodes.Add(directory.Name);
于 2013-03-18T21:36:04.617 回答
0

我想这是你想要的。

var directories = Directory.GetDirectories("c:\\users");
foreach (string directoryName in directories)
{
    var directory = new DirectoryInfo(directoryName);
    var node = new TreeNode(directory.Name);
    node.ImageIndex = 1;

    foreach (FileInfo file in directory.GetFiles())
    {
        if (file.Exists)
        {
            var nodes = node.Nodes.Add(file.Name);
            nodes.ImageIndex = 2;
        }
    }
    treeView1.Nodes.Add(node);
}
于 2013-03-18T21:42:08.223 回答