C# – Autocomplete Textbox

There are times when you’ll need an autocomplete textbox. Autocomplete textbox makes the user’s life easier. It shows suggestions as the user types. In case of a web browser, if you type “goo” it will automatically show all the suggestions starting with or containing “goo” like “Google, Goofy” etc. It really helps both you or your users when hunting for something. Of course, it seems difficult to set up but really it isn’t that hard. Enough talk! Let’s get on with it.

 

Fortunately, textbox has a built-in autocomplete feature! We don’t have to do any coding.

You can either set it up from the Designer (if you are using Visual Studio or #Develop) or do it via code. It is simple both ways. Lets do it!

Setting up AutoComplete

Auto complete textbox

 

For setting up autocomplete you’ll have to use three properties of the TextBox class — AutoCompleteSource, AutoCompleteCustomSource and AutoCompleteMode. Here’s an explanation of these properties:

AutoCompleteSource is the source of the suggestions. You can assign it CustomSource if you want to use custom suggestions or use other auto sources like FileSystem, HistoryList etc. Below are all the available sources:

  • FileSystem: This will show suggestions from the file system i.e files stored on the computer. Like if you write “C:\” it’ll show all the files stored on C: drive.
  • FileSystemDirectories: This is same as FileSystem but it shows directory names instead of file names.
  • HistoryList: This will show URLs from Internet Explorer’s history.
  • RecentlyUsedList: A list of recently used applications, folders, and URLs (from internet explorer).
  • AllUrl: This specifies an equivalent of HistoryList and RecentlyUsedList as the source.
  • AllSystemSources: Specifies an equivalent of AllUrl and FileSystem as the source.

AutoCompleteModes are of 3 types. Suggest, Append and SuggestAppend:

  • Suggest will show suggestions in a drop-down as the user types.
  • Append will auto complete as you type. Like if you write “Goo” it’ll automatically make it “Google”.
  • SuggestAppend will do both Suggest/Append.

AutoCompleteCustomSource is collection of custom suggestions. It will be used when you assign “CustomSource” as “AutoCompleteSource”.

Okay enough explanations. Lets make an autocomplete textbox now.

Using Designer:

If you are using the Designer, then all you have to do is to select your TextBox and change those three properties (explained above). For instance, if you want to use custom suggestions then use “CustomSource” and add the custom suggestions to “AutoCompleteCustomSource” (don’t forget to set up AutoCompleteMode). Debug your project and see! Its that easy :-). Don’t forget that you can also use all the other sources like FileSystem, HistoryList etc.

Via Coding:

Here’s an example:

That’s it.

If you have any questions, don’t hesitate to post a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *