• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 659
  • Last Modified:

Populating a combo box with files in a folder

Hi,
I want to be able to populate a combo box with files in my directory(c:\myTemplates). The files are actually word templates which I will show on the combo box. They have an extension .dot and I do not want the extension .dot to show in the combo box.  How can I handle this please using c#(windows application)

Folder structure
C:\MyTemplates\ Template1.dot
                          Template2.dot
                          Template3.dot

combo box should show Template1
                                   Template2
                                   Template3

What is the best way to do this. Is it possible with Xml file???

Thanks.
0
Sirdots
Asked:
Sirdots
  • 3
  • 2
1 Solution
 
sharpnetCommented:
You'll want to use either (probably both) the DirectoryInfo object or the FileInfo object.  They are part of the System.IO namespace.

In a list box, it could look like:

DirectoryInfo theFolder = new DirectoryInfo("c:\\myTemplates");

// list all files in a folder
foreach (FileInfo nextFile in theFolder.GetFiles())
{
   listBox1.Items.Add(nextFile.Name); // you can do some string work here to cut off the extension
}

Hope this helps.

Nick
0
 
SirdotsAuthor Commented:
This helps a lot. I appreciate it. I am still having some trouble cutting off the strings from the back i.e getting off  ".dot"

Thanks.
0
 
SirdotsAuthor Commented:
I will also prefer to  have the first item as a default value on the combo box.

Thanks.
0
 
sharpnetCommented:
well, you can do something like:

foreach (FileInfo nextFile in theFolder.GetFiles())
      {
            string[] fileName = nextFile.Name.Split('.'); // note the single quotes, not double quotes.
            listBox1.Items.Add(fileName[0]);
      }

The split function will break the filename into two parts (assuming there is only one dot in the filename) and place each half of the file name into an array.  The first index in the array (0) will be the filename, the second index (1) will be the extension.  So, you can just call fileName[0] to get the first portion of the filename and add it to your list box or combobox...

Nick
0
 
sharpnetCommented:
If you're using a combobox, just use

comboBox1.SelectedIndex = 0;

 to make the first item in the list as the default.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now