CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jun 2009
    Posts
    2

    Exclamation Populating listbox with file names

    Here's the code that I'm currently using in VS C# 2010:
    // update listbox
    DirectoryInfo dir = new DirectoryInfo((Application.StartupPath + "\\CustomerCollectionData\\"));
    // create array containing filenames
    FileInfo[] file = dir.GetFiles();
    // print out the file names
    FileInfo fiTemp;
    foreach (fiTemp in file)
    {
    listBox1.Items.Add(fiTemp.Name);
    }

    I get an error under the "foreach (fiTemp in file)" line; specifically red-underlined "fiTemp" & "in" saying:

    "Type or namespace name 'fiTemp' could not be found"
    (under "fiTemp")

    and
    "Type and identifier are both required in a foreach statement"
    (under "in")

    According to my research on this topic, the syntax should be right, unless I missed something...
    Anyone know what the issue is?

  2. #2
    Join Date
    Sep 2000
    Location
    FL
    Posts
    1,452

    Re: Populating listbox with file names

    I am not completely sure, but from the error messages it sounds like you need to change the code to this.

    Code:
    foreach (FileInfo fiTemp in file)
    {
        listBox1.Items.Add(fiTemp.Name);
    }
    The error message "Type and identifier are both required in a foreach statement" means that you need to declare what type of object you are looking for in "file". Don't declare the object beforehand, it must be declared in the foreach.

  3. #3
    Join Date
    Jun 2009
    Posts
    2

    Re: Populating listbox with file names

    Well, you were partly right. I can't believe I didn't catch it before.
    This:

    Code:
    FileInfo fiTemp;
    I was declaring it there... Then here:

    Code:
    foreach (FileInfo fiTemp in file)
    I was basically redeclaring it...

    Thanks so much

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured