Auto-complete Textbox
Implementing an auto-complete textbox is a rather easy task, as it is all built in to WinForms.
I will be using and referring to a text box here named textBox1.
Auto-complete Mode
This setting will determine whether the auto-complete items will be suggested to your user or appended onto their text (or even both):
Suggest:

Append:

Suggest and Append:

You can set the mode either in the Properties window in the IDE or via code:
textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend; |
Auto-complete Source
We will use a custom auto-complete source, so we specify the strings easily:
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource; |
You can view MSDN for the other types of sources you can use such as the File System and Recently Used.
Auto-complete Custom Source
I will name the auto-complete collection, AutoCompleteList:
AutoCompleteStringCollection AutoCompleteList = new AutoCompleteStringCollection(); |
To add items to our list:
AutoCompleteList.Add("http://www.google.com/"); AutoCompleteList.Add("http://www.yahoo.com/"); AutoCompleteList.Add("http://www.bing.com/"); |
To get more functionality out of our auto-complete box, we are able to load the items from a text file:
foreach (string AutoCompleteItem in System.IO.File.ReadAllLines(Application.StartupPath + "\\AutoList.txt")) { AutoCompleteList.Add(AutoCompleteItem); } |
This code will look for a file called AutoList.txt in the same directory you are running your application from, it will then load and add each new item. Of course your items could come from a number of other sources including a database.
We then need to link the source to the text box:
textBox1.AutoCompleteCustomSource = AutoCompleteList; |
Complete Code
AutoCompleteStringCollection AutoCompleteList = new AutoCompleteStringCollection(); foreach (string AutoCompleteItem in System.IO.File.ReadAllLines(Application.StartupPath + "\\AutoList.txt")) { AutoCompleteList.Add(AutoCompleteItem); } textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource; textBox1.AutoCompleteCustomSource = AutoCompleteList; textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend; |
Warnings
- Auto-complete will not work on multi-line text boxes.