U.Savas U.Savas - 27 days ago 8x
C# Question

How to enable auto complete for a list of files in ComboBox

I tried to get all the ".txt" files on the user's desktop and display them in the

as a custom source, as shown below. By the way I created the
through IDE. The code below is within the

string desktop_path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string[] files_on_desktop = System.IO.Directory.GetFiles(desktop_path, "*.txt");
AutoCompleteStringCollection file_collection = new AutoCompleteStringCollection();
comboBox1.AutoCompleteCustomSource = file_collection;
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;

This seems not to work although I tried in many different ways as well as with many supporting code such as "

It doesn't show files when I open drop-down, also it doesn't show files when I start typing.

Actually, whenever I try to do things dynamically which I can do on IDE, I got some sort of problems.


Those files which you added include path and file name, for example C:\Users\R.Aghaei\Desktop\Test.txt. If you need to see only filename, you can use System.IO.Path.GetFileName(x) to get file names only.

Also if you want to show those filenames just for autocomplete, a TextBox would be enough. If you want to use a ComboBox it's better to add those files to Items collection and then set auto complete source to list items.

AutoCompleteSource is different from Items. You should add those file names to Items to be shown when you click on drop down button. To do so, just use comboBox1.Items.AddRange(files_on_desktop);. Then just set AutoCompleteSourceMode to AutoCompleteSource.ListItems. Then you have both items and auto complete. If you click on drop down button, you will see all available items. If you only type in the box, auto-complete will work for you.

string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var files = System.IO.Directory.GetFiles(desktopPath, "*.txt")
                                .Select(x => System.IO.Path.GetFileName(x)).ToArray();
comboBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
comboBox1.AutoCompleteSource = AutoCompleteSource.ListItems;