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

2
  • 2
    Looks like the error would be generated on the first line after the initial foreach... TreeView is a class name and probably not the name of your object. What is the TreeView object named? Commented Mar 18, 2013 at 21:35
  • Try replacing the name TreeView with the actual name of the control. Commented Mar 18, 2013 at 21:36

2 Answers 2

3

TreeView is not a static class which is why you're getting that error message. You should change where you've used TreeView to the actual name of your instance.

For example:

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

should be

//myTreeView is the name of my TreeView object
TreeNode node = myTreeView.Nodes[0].Nodes.Add(directory.Name);
Sign up to request clarification or add additional context in comments.

Comments

0

I think what you want it this.

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);
}

2 Comments

thanks for your help it worked awsome. i need help in the following, i have Form2 with adobe pdf reader tool in it, and some of the files in Form1 are pdf, how can i preview the pdf files in treeview in Form1 in adobe pdf reader in Form2
Glad it worked for you. As for the Adobe Reader, the question isn't related to this thread but you can look into "Adobe Reader ActiveX Control". There is a good article a this link which shows you exactly how to do this. c-sharpcorner.com/uploadfile/hirendra_singh/… :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.