Tuesday, 7 January 2014

Winforms C# - AutoComplete for Textbox and ComboBox

Recently I came across the autocompletion feature in WinForms TextBox control.
My requirement was to have an autocomplete textbox with the file paths and file names like windows explorer address bar.
Instead of writing the whole functionality myself I was really excited to find the built in autocomplete feature with windows forms controls.
You need to set 2 properties (AutoCompleteSource and AutoCompleteMode) of Textbox and ComboBox controls to use the built in AutoComplete features. The properties can be set either at design time or at runtime via code.

Both the properties are enumerations. The values are explained below:

AutoCompleteSource Enumeration :
  • AllSystemResources – Specifies the equivalent of FileSystem and AllUrl as the source. This is the default value when AutoCompleteMode has been set to a value other than the default.
  • AllUrl – Specifies the equivalent of HistoryList and RecentlyUsedList as the source.
  • CustomSource – Specifies strings from a built-in AutoCompleteStringCollection as the source.
  • FileSystem – Specifies the file system as the source.
  • FileSystemDirectories – Specifies that only directory names and not file names will be automatically completed.
  • HistoryList – Includes the Uniform Resource Locators (URLs) in the history list.
  • ListItems – Specifies that the items of the ComboBox represent the source.
  • None – Specifies that no AutoCompleteSource is currently in use. This is the default value of AutoCompleteSource.
  • RecentlyUsedList – Includes the Uniform Resource Locators (URLs) in the list of those URLs most recently used.
AutoCompleteMode enumeration:
  • Append – Appends the remainder of the most likely candidate string to the existing characters, highlighting the appended characters.
  • None – Disables the automatic completion feature for the ComboBox and TextBox controls.
  • Suggest – Displays the auxiliary drop-down list associated with the edit control. This drop-down is populated with one or more suggested completion strings.
  • SuggestAppend – Applies both Suggest and Append options

Example: AutoComplete with file path on typing in the Textbox. (Like Windows Explorer Address Bar and Run Dialog)
Textbox1.AutoCompleteSource = AutoCompleteSource.FileSystem;
Textbox1.AutoCompleteMode = AutoCompleteMode.Suggest;

1 comment:

  1. Autocomplete combobox example...

    comboBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
    comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
    AutoCompleteStringCollection combData = new AutoCompleteStringCollection();
    comboBox1.AutoCompleteCustomSource = combData;

    Full Source....Autocomplete Combobox