Subscribe to Sergio Tapia - Lost in the GC.        RSS Feed

Creating a simple autocomplete texbtox using C# for Windows Forms.

Icon 4 Comments
First let's create a table in our database that's called Person.

create table Person(
PersonID int primary key identity(1,1),
Name nvarchar(256)

Now drag a TextBox control to your design and change the AutoCompleteMode property. We'll be using the Suggest option.

Next, change the AutoCompleteSource to CustomSource.

Ok, great!

Now, using Entity Framework 4, we'll retrieve a list of Names from the database.

AutoCompleteStringCollection names = new AutoCompleteStringCollection();

private void MainForm_Load(object sender, EventArgs e)
    OurEntities db = new OurEntities();
    var peopleFromDatabase = db.People;
    foreach (var p in peopleFromDatabase)

    textBox1.AutoCompleteCustomSource = names;

Posted Image

And that wraps it up! :D You now have an autocomplete textbox.

I'd like to ask the community where would the best place to actually retrieve the information be? On KeyDown? But that would hammer the database a lot. Maybe on a Timer, refresh the list of known names?

Let's brainstorm!

4 Comments On This Entry

Page 1 of 1


01 February 2011 - 02:56 PM
One drawback of your method is that you are loading an entire collection locally. What if there are 1,000 suggestions? What about 7,000,000? That would have a performance footprint on the app that will manage the storage. There is nothing wrong with querying a database as long as you optimize the query and it extracts exactly the words needed with a char limit, so that you won't have to load hundreds of results at once.

Sergio Tapia 

01 February 2011 - 03:10 PM
Then how about, onkeydown, check the textBox.Text length and from three characters onwards start fetching results? That would drastically cut down the result size.

Any other suggestion?


01 February 2011 - 05:51 PM
better yet, create a property that allows you to set the minimum number of chars needed to start fetching results.


01 February 2011 - 05:52 PM
you could also set a size limit on the number of items returns, like only return the top 100 results
Page 1 of 1

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)

About Me

Posted Image

Bienvenidos! I'm a USA ex-pat living in Bolivia for the past 10 years. Web development is my forte with a heavy lean for usability and optimization. I'm fluent in both English and Spanish. I guest write for the popular Python website Python Central. Visit my website.