开发者

How to filter a listbox using a combobox

开发者 https://www.devze.com 2022-12-20 19:36 出处:网络
How do I filter items in a listbox using a combobox using c# and windows forms? the listbox contains files an开发者_运维知识库d the combobox needs to filter them by their extension

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

the listbox contains files an开发者_运维知识库d the combobox needs to filter them by their extension

Please help I'm new to programming


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);
}

Filtering a texbox with a combobox


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.


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消