Click here to Skip to main content
15,936,247 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
Good morning
I think my question is very simple for your experience
one combobox with specific path give me the folders that have in it
I want when i select one folder from combobox the files in the folder placed in the list box.

What I have tried:

C#
private void Form1_Load(object sender, EventArgs e)
{
    DirectoryInfo obj = new DirectoryInfo(@"C:\");
    DirectoryInfo[] folders = obj.GetDirectories();
    comboBox1.DataSource = folders;            
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    // ???     
}
Posted
Updated 4-Aug-20 22:26pm
v4
Comments
BillWoodruff 5-Aug-20 8:20am    
You may have what you need, now, however, I'd like to suggest you use a TreeView to represent the possibly nested directory structures. If you want to see some code for that: just ask.
TheRealSteveJudge 5-Aug-20 8:54am    
This is a brilliant idea!

First of all you must cast "sender" which is just an object
to "ComboBox".
Then you must get "SelectedValue".
Finally you must get the files that are in the selected directory and use it as data source for the ListBox.
C#
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    var comboBox = (ComboBox) sender;

    var directoryInfo = comboBox.SelectedValue as DirectoryInfo;

    if(directoryInfo == null) return;

    var filenames = Directory.GetFiles(directoryInfo.FullName);

    listBox1.DataSource = filenames;

    var shortFilenames = filenames.Select(x => Path.GetFileName(x)).ToList();

    listBox1.DataSource = shortFilenames;
}
 
Share this answer
 
v4
Comments
Stm21 5-Aug-20 4:20am    
Thank you for the quick response
the code work but in the list box the results is c:\bla bla bla...
i want only the filename not all the path
TheRealSteveJudge 5-Aug-20 4:33am    
Please have a look at the updated solution.
Stm21 5-Aug-20 4:34am    
Thank you so so so so so much for your help.
TheRealSteveJudge 5-Aug-20 4:35am    
You're welcome!
BillWoodruff 5-Aug-20 8:21am    
+5
 
Share this answer
 
Comments
BillWoodruff 5-Aug-20 8:16am    
+5 unwarranted down-vote countered.
Richard MacCutchan 5-Aug-20 11:15am    
Thanks Bill.
Code in combobox selected change would be roughly:
C#
String[] files = System.IO.Directory.GetFiles("combobox selected path of folder");
for (i = 0; i < files.Length; i++)
{
    listBox1.Items.Add(files[i]);
}

try out!

Reference Updated: Directory.GetFiles Method (System.IO) | Microsoft Docs[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900