Click here to Skip to main content
Click here to Skip to main content

WPF Autocomplete Textbox Control

By , 31 May 2008
 

Introduction

This article demonstrates some basic steps on how to build an auto complete textbox custom control with WPF. I have looked at many auto completion textbox solutions, most of them suffered performance issues when filled with large amount of entries. This implementation attempts to mask that problem by not building the suggested list until the user is done typing.

Background

I needed an autocompletion textbox for my application that can search based not just on name but also on keywords. I found the solution posted by pfemiani. I like his idea of searching by keywords but the solution does not work for my WPF application without extensive modification. Then I came across a WPF solution from AskErnest.com using a textbox and combobox controls, so I decided to build my code upon that.

Ernest's suggestion is pretty simple, there are two children in the control, Textbox and Combobox. On the TextBox's TextChanged event, we would populate the list for the combobox using words matching the text in the textbox. On the ComboBox's SelectionChanged event, we set the text in the textbox using the content of the selected item of the Combobox. This works very well except that Ernest is only doing name matching and his blog doesn't provide the complete source code.

Another challenge that I'm facing is performance issue. My autocompletion textbox is backed by several thousand entries from a database, on some keyword I could have over 300 hits. Populating the combobox on every user keystroke feels sluggish. My solution is to start a timer on TextChanged event and populate the combobox list only when the timer expires. I tried this on my large database and it works beautifully. I can type a long name and not feel like I'm on a 286.

Using the Code

To use this custom control in your application, you simply add the following files...

  1. AutoCompleteEntry.cs
  2. AutoCompleteTextBox.xaml
  3. AutoCompleteTextBox.xaml.cs

... to your project. Next, in the XAML file that you would like to use the auto complete textbox custom control, add this line to the header block.

xmlns:local="clr-namespace:WPFAutoCompleteTextbox"

Then in the XAML code, where you want to place the auto complete textbox, add:

<local:AutoCompleteTextBox Height="23" Width="240" x:Name="textBox1" 
    DelayTime="500" Threshold="2"/>

In my example code, the name of the textbox is textBox1. You can get or set the text in the textbox by referring to textBox1.Text. The DelayTime property is the amount of time (in ms) that you want to delay after the user starts typing before populating the list. Leaving the DelayTime unset will default to 0, which is populating immediately after each user keystroke. The Threshold property controls the number of characters threshold, at or over that at we will start suggesting.

In the code behind of my example, I manually populate the search entries with a variety of cars and models.

textBox1.AddItem(new AutoCompleteEntry
    ("Toyota Camry", "Toyota Camry", "camry", "car", "sedan"));
textBox1.AddItem(new AutoCompleteEntry
    ("Toyota Corolla", "Toyota Corolla", "corolla", "car", "compact"));
textBox1.AddItem(new AutoCompleteEntry
    ("Toyota Tundra", "Toyota Tundra", "tundra", "truck"));
// null matching string will default with just the name
textBox1.AddItem(new AutoCompleteEntry("Chevy Impala", null));
textBox1.AddItem(new AutoCompleteEntry
    ("Chevy Tahoe", "Chevy Tahoe", "tahoe", "truck", "SUV"));
textBox1.AddItem(new AutoCompleteEntry
    ("Chevrolet Malibu", "Chevrolet Malibu", "malibu", "car", "sedan"));

If for example, the user types in "car", all the entries with the "car" keyword will be suggested.

I hope you find this solution helpful. If you find any errors or have questions, feel free to contact me.

History

  • 30th May, 2008: First release

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

thomastn
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralThanks Pinmemberwangsy8011 Jun '12 - 17:57 
Thanks
QuestionAdd ItemTemplate PinmemberJenami676 Apr '12 - 21:13 
I want a list like firefox address bar. when user search something shows a list with an image and some other info from database.
can i do it with this control.
GeneralMy vote of 5 Pinmembershynet25 Dec '11 - 9:27 
Beautiful control! missing functionality of removing auto completions entries, except that works well!
GeneralThanks. An alternative way. Pinmemberpoporopo15 Jun '11 - 9:29 
Thanks for sharing our code.
Here is an alternative: http://code.google.com/p/kocontrols/
GeneralMy vote of 4 Pinmemberlixie132422 May '11 - 17:02 
Nice Control
GeneralAccept items only from list Pinmemberboki_thegame26 Mar '11 - 7:46 
I want in text box to accept (validate) items only from list not something written from user ?
GeneralMy vote of 5 Pinmemberairtongomeslima17 Mar '11 - 16:46 
Perfect! A
QuestionHow can i reference a class from the AutoCompleteBox Pinmemberabetterword7 Jan '11 - 9:13 
This AutoCompletebox works great, but how do i reference a class in my main xaml cs file from the AutoCompleteTextBox cs?
GeneralMy vote of 5 Pinmembervegbruiser27 Oct '10 - 3:03 
Excellent work, thanks.
Generalone more thing PinmemberdotNiemand27 May '10 - 0:31 
public void ClearItems()
{
autoCompletionList.Clear();
}
 
JIC if you need to clean TB up
GeneralSelected Item Event improvement PinmemberdotNiemand27 May '10 - 0:06 
add this
        #region Events
           
        public event EventHandler<EventArgs> SelectedItemChanged;
        
        #endregion
 
and this
 
            // set up the text box and the combo box
            comboBox = new ComboBox();
            comboBox.IsSynchronizedWithCurrentItem = true;
            comboBox.IsTabStop = false;
            comboBox.SelectionChanged += new SelectionChangedEventHandler(comboBox_SelectionChanged);
            comboBox.PreviewKeyDown += new KeyEventHandler(comboBox_KeyDown);

        void comboBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && comboBox.SelectedItem != null && SelectedItemChanged != null)
                SelectedItemChanged(this, new RoutedEventArgs());
        }
 
and you'll be able to handle enter key quickly
Generalsmall improvement - down button PinmemberdotNiemand26 May '10 - 23:49 
        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            if (e.Key == Key.Down && comboBox.IsDropDownOpen)
            {
                comboBox.Focus();
                comboBox.SelectedIndex = 0;
            }
 
            base.OnPreviewKeyDown(e);
        }
 
add this code to textbox .xaml.cs file and it will handle down click, so there's no need to use mouse to select an option
GeneralAdding focus after selecting from the combobox. PinmemberBudsy29 Mar '10 - 22:27 
One nice feature to add is restoring focus to the AutoCompleteTextBox after selecting from the combobox, and placing the caret at the end of the text in the box. Add the two lines marked "// add this" to this method in AutoCompleteTextBox.xaml.cs
 
private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (null != comboBox.SelectedItem)
{
insertText = true;
ComboBoxItem cbItem = (ComboBoxItem)comboBox.SelectedItem;
textBox.Text = cbItem.Content.ToString();
textBox.Focus(); // add this
textBox.CaretIndex = textBox.Text.Length; // add this
}
}
 
Budsy
Questionadditional PinmemberComan Ovidiu24 Feb '10 - 1:39 
I want autosuggestion for any word, not only for the first.
You know any solution?
AnswerRe: additional PinmemberBudsy29 Mar '10 - 22:36 
Question[My vote of 1] Hey - what's this keyboard for? Pinmembertonyt21 Feb '10 - 16:24 
Was providing a reasonably functional emulation of the native autocomplete a problem with WPF (I'm referring to responding to the up/down arrow key when the list pops up)?
GeneralIssue with WPF AutoComplete TextBox with Chinese and Japanese inputs Pinmembersandyyyyyyyyyy18 Nov '09 - 23:35 
Well I am using our WPF autoComplete textbox and its working excellent in all the languages.
 
But when I use chinese or japanese language as input language it causes the application to crash.
 
this has been a serious issue I have been facingConfused | :confused: Confused | :confused: Confused | :confused:
 
Please help me out in this
GeneralMy vote of 2 Pinmemberrealvasche23 Oct '09 - 7:36 
Autocomplete with no keyboard nav? You have to be kidding.
Questionchinese IME issue Pinmembernnnnimisha5 Aug '09 - 20:17 
Hello All,
 
The control doesnot seems to be working when input is being made through
Chinese IME 3.0 and the entire applications crashes.
 
Can you suggest any solution to the issue.Confused | :confused: Confused | :confused: Confused | :confused:
QuestionHow can I change the Background Color of the AutoComplete TextBox? Pinmembermicrosoft_kc23 Jun '09 - 20:59 
Hi,
 
I checked a lot.... but unfortunately, I am unable to change the background color of the autocomplete textbox. D'Oh! | :doh:
 
Please help me to find out the same. I need it ASAP.
 
Thank you in advance.
 
Regards,
- Kunal Chowdhury (My Blog)
 

AnswerRe: How can I change the Background Color of the AutoComplete TextBox? PinmemberTrond Andersen22 Oct '09 - 4:08 
GeneralNice One Pinmemberkapil bhavsar7 May '09 - 23:49 
How bout porting it to Silverlight ..
GeneralMy vote of 2 PinmemberRandomEngy14 Apr '09 - 7:44 
Solution is hack-like, autocomplete is not responsive and does not use async.
QuestionWait hold on... is your ComboBox hiding behind the text field? PinmemberMember 403000514 Apr '09 - 7:41 
It seems like you just have a ComboBox and are hiding the main portion of it with your TextBox, and are opening it programatically, letting the drop-down peek out. That seems a little bit hack-like to me.
GeneralThanks!! PinmemberDZaK8319 Mar '09 - 13:11 
Simple and work great! Smile | :)
 
Bests,
Jacek Ciereszko
 
Work smart not hard

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 31 May 2008
Article Copyright 2008 by thomastn
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid