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

Populate a ListBox with File Names from a Directory

I have a listbox named lstFiles. and a directory named C:\MyApp\MyFiles.

The directory contains 12 files whose extension is .txt.

How can I populate the listbox with file names in alphabetical order?

  • 2
1 Solution
Mike TomlinsonMiddle School Assistant TeacherCommented:
*Assuming WinForms as this really doesn't sound like ASP.Net...

Try something like this:
        private void button1_Click(object sender, EventArgs e)
            string path = @"C:\MyApp\MyFiles";
            var files = (from file in System.IO.Directory.GetFiles(path, "*.txt")
                         orderby System.IO.Path.GetFileNameWithoutExtension(file) ascending 
                         select new
                             Name = System.IO.Path.GetFileNameWithoutExtension(file),
                             FullPath = file
            lstFiles.DisplayMember = "Name";
            lstFiles.ValueMember = "FullPath";
            lstFiles.DataSource = files;

        private void lstFiles_SelectedIndexChanged(object sender, EventArgs e)
            if (lstFiles.SelectedIndex != -1)
                label1.Text = lstFiles.SelectedValue.ToString();

Open in new window

DovbermanAuthor Commented:
This is working for asp.net in a web form.

files[2] returns

{ Name = "AMEX_20131017", FullPath = "C:\\Develop\\Apps\\StockPro\\Data\\AMEX_20131017.txt" }
    FullPath: "C:\\Develop\\Apps\\StockPro\\Data\\AMEX_20131017.txt"
    Name: "AMEX_20131017"

DovbermanAuthor Commented:

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

Train for your Pen Testing Engineer Certification

Enroll today in this bundle of courses to gain experience in the logistics of pen testing, Linux fundamentals, vulnerability assessments, detecting live systems, and more! This series, valued at $3,000, is free for Premium members, Team Accounts, and Qualified Experts.

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