Link to home
Start Free TrialLog in
Avatar of Sirdots
Sirdots

asked on

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.
Avatar of sharpnet
sharpnet

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
Avatar of Sirdots

ASKER

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.
Avatar of Sirdots

ASKER

I will also prefer to  have the first item as a default value on the combo box.

Thanks.
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
ASKER CERTIFIED SOLUTION
Avatar of sharpnet
sharpnet

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial