views:

545

answers:

3

How do I filter items in a listbox using a combobox using c# and windows forms?

the listbox contains files and the combobox needs to filter them by their extension

Please help I'm new to programming

A: 

This is almost an exact duplicate from your last question. The same answer applies.

On the selected index changed event of the combo box, I'd add the items to your listbox based off of the filter selected from your combobox. You can use System.IO.DirectoryInfo to filter your directory given a file extension.

//Clear your listBox before filtering if it contains items
if(yourListBox.Items.Count > 0)
   yourListBox.Items.Clear();
DirectoryInfo dInfo = new DirectoryInfo(<string yourDirectory>);                                 
FileInfo[] fileInfo = dInfo.GetFiles("*" + <string yourChosenFileExtension>);
foreach (FileInfo file in fileInfo)
{  
   yourListBox.Items.Add(file.Name);
}

http://stackoverflow.com/questions/2291417/filtering-a-texbox-with-a-combobox/2291472#2291472

Aaron
ye i know sorry i've decided to change it to a listbox just makes more sense.I've tried this code but it only seems to add it to the bottom of the list rather than filter it
roller
You are correct. My apologies. See my edit above. Clear the listbox if it contains anything before applying the filter.
Aaron
THANKYOU!!!!! It works awsome now. Thankyou Thankyou Thank you
roller
Glad I could help. Don't forget to accept this answer as the correct answer :D.
Aaron
You could also accept my answer on your other question if you were inclined to do so ;).
Aaron
A: 

Well you could load the items in a datatable and assing the datatable to the listbox.datasource property. Then you can set the Filter attribute on the DataTable to filter the items.

Another way is to hold the items in a separate list, an assing a linq query implementing the filter to the ListBox.DataSource property once the SelectedItem of the ComboBox changes.

Obalix
A: 

you need to work over the DataSource for ListBox, say it is a List of file names
complete with extentions:

List<string> files = new List<string>();  // sample DataSource

get the selected extension from the ComboBoxto and use it to order ListBox DataSource (file).

       string fileExtemsion;               

       var orderedFiles = files.OrderBy(o => o.EndsWith(fileExtemsion)); // order          

       listBox.DataSource = orderedFiles;       // setting Datasource 
       listBox.DataBind();
Asad Butt