displaying file order in a listbox

Hi,

I am using a button and a listbox in my winform.
When I click the button, a user can select multiple files at the same time.
However, always the last selected file goes to the top of the list in the listbox.
how can I list the files in the listbox in order to be selected?  For example, if I select the 3 doc files with following order:1.doc, 2.doc and 3.doc, and add all of them at the same time, the list of file should be displayed as 1.doc, 2.doc, and 3.doc from top to bottom.

The following codes are for the button.

        private void button1_Click_1(object sender, EventArgs e)
        {
            dlg.Multiselect = true;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                foreach (string fileName in dlg.FileNames)
                {
                    textBox1.Text = fileName;
                    listBox1.Items.Add(Path.GetFileName(textBox1.Text));
                }
            }
        }
muffintwinklyAsked:
Who is Participating?
 
jlj1527Commented:
Because the OpenFileDialog always return you the results like this:
- The first element of FileNames array is the last file you selected
- The second, third .. element are ordered by the order you selected the files.
=> So your work is Adding the first Element of FileNames array at the end.


try this:
if (dlg.ShowDialog() == DialogResult.OK)
{
     for (int i = 1; i < dlg.FileNames.Length; i++)
    {
             textBox1.Text = dlg.FileNames[i];
             listBox1.Items.Add(Path.GetFileName(textBox1.Text));
     }
    textBox1.Text = dlg.FileNames[0];
     listBox1.Items.Add(Path.GetFileName(textBox1.Text));

}

 
0
 
muffintwinklyAuthor Commented:
thanks! it works great.
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.

All Courses

From novice to tech pro — start learning today.