Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » Windows Forms C# » AutoComplete TextBox in C#

AutoComplete TextBox in C#

Auto completion is a new feature added to Windows Forms 2.0 controls. In this article, I will show how to use the auto completion feature in your applications.

Author Rank :
Page Views : 108721
Downloads : 2359
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
AutoCompleteSample.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Most of the developers are familiar with the auto completion text feature available in browsers, search controls and other controls. The auto completion feature is when you start typing some characters in a control, the matching data is loaded automatically for you.

In Visual Studio 2005, some of the controls support this feature including the ComboBox and the TextBox controls. By using these features, we can build Internet Explorer like auto completion functionality in our Windows Forms applications.

Now, we can have a combo box that completes URLs as soon as you type any character. For example, in Figure 1, I typed "c-s" and I see all the URLs starting with "c-s".

AutoCompleteImg1.gif

Figure 1. Auto Completion in a ComboBox

The AutoCompleteSource and AutoCompleteMode properties of the TextBox and ComboBox controls allow developers to provide automatic completion text feature. You can set both of these properties at design-time as well as at run-time. If you click on AutoCompleteSource drop down, you will see all the options in the drop-down list. See Figure 2.

AutoCompleteImg2.GIF

Figure 2. AutoCompleteSource options

Figure 3 shows AutoCompleteMode options.

AutoCompleteImg3.GIF

Figure 3. AutoCompleteMode options

You can also set these properties at run-time using the following code:  

comboBox1.AutoCompleteSource = AutoCompleteSource.AllSystemSources;
comboBox1.AutoCompleteMode =
AutoCompleteMode.SuggestAppend;

The AutoCompleteSource Enumeration has following members:

  • 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.

The AutoCompleteMode enumeration has following members:

  • 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.

Loading Custom Source 

We can also specify a custom source from where the listing will be loaded. If you click on the AutoCompleteCustomSource property, it will open the String Collection Editor, where we can add our strings. For example, I add following strings to the strings list. See Figure 4.

AutoCompleteImg4.GIF

Figure 4. Custom Source strings

Now we need to set AutoCompleteSource to CustomSource:

comboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;

And when I run and type "v" in the combo box, I see VB.NET Heaven. See Figure 5.

AutoCompleteImg5.GIF

Figure 5. Custom Source listing

We can also create AutoCompleteStringCollection programmatically. The following code creates an AutoCompleteStringCollection, adds strings to the collection, and sets it to the AutoCompleteCustomSource of the ComboBox. 

// AutoCompleteStringCollection
AutoCompleteStringCollection data = new AutoCompleteStringCollection();
data.Add(
"Mahesh Chand");
data.Add(
"Mac Jocky");
data.Add(
"Millan Peter");
comboBox1.AutoCompleteCustomSource = data;

Now running the sample and typing "m" in the ComboBox loads the data as shown in Figure 6.

AutoCompleteImg6.GIF 

Figure 6. Loading custom data

Summary

The AutoComplete feature of ComboBox and TextBox controls allow us to set the auto complete text feature. In this article, we saw how to use this feature in our application at design-time as well as at run-time.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
Autocomplete by shitesh On March 13, 2006

hi!

this is shitesh shukla(new to c#.net).

i tried yours autocopmlete feature in combo box but there is no such

attribute in the framework which i am using.i am using version1.1(2001-2002).

is autocomplete feature of combo box is newly added in advance version?

thanks and regards

Shitesh shukla

Reply | Email | Modify 
Re: Autocomplete by Mahesh On March 13, 2006
This feature is available in .NET 2.0 or later versions only.
Reply | Email | Modify 
Autocomplete delay by Michael On June 13, 2006

Thanks for the article.

We've now used autocomplete in our application and, quite simply, the users don't reckon it's working!  This is because the "restart" delay is too quick - they type a few characters, pause for thought, and type the rest - only for the autocomplete to have restarted (we use the append type).

Is there any control over this delay?  In our comboboxes the "key" they are trying to find (from a list of thousands) is up to 15 characters long (letters and numbers) - so they need to be able to type this in slowly!

Thanks,

Dr. Michael Dye.

Reply | Email | Modify 
Re: Autocomplete delay by Donald On August 21, 2008
Did you ever discover a solution to this time delay problem?  I am having the same issue ...  User stops entering data for a second and the AutoComplete restarts from the beginning.
Reply | Email | Modify 
Re: Re: Autocomplete delay by Michael On September 1, 2008

Good morning,

No, I'm afraid not!  Been one of the bug-bears of the application that's just festered...  In a way people have got used to it, but that's not really good enough!

Thanks,

Dr. Michael Dye

Reply | Email | Modify 
Re: Autocomplete delay by Mahesh On May 24, 2010
I would not use this for 1000s of items. To do that, you should implement a Webservice and consume it and get only data that matches the keywords. You will make a call to the Webservice on every character typed in the TextBox.

Good luck!
Reply | Email | Modify 
query by nagamani On November 15, 2007

very urgent

hello sir i want to select Mac Jocky (combobox item) by pressing Return key

Reply | Email | Modify 
Re: query by Mahesh On May 24, 2010
I think it does select.
Reply | Email | Modify 
display autocomplete list when control gets focused or clicked by daniel On January 16, 2008
I would like to know if there's any way I can display the auto-complete list as soon as the control gets focused? (onclick should work also)
Reply | Email | Modify 
Re: display autocomplete list when control gets focused or clicked by Mahesh On May 24, 2010

That kind of defeats the purpose of AutoComplete ;). If you just want to load all items anyway, add items to the ComboBox.

Reply | Email | Modify 
AutoComplete with TextBox in DataGridView by Allan On April 10, 2009
I can get autocomplete to work with a standalone TextBox. But with the following C# code, I never see the auto complete drop down. Also, is it possible to see the auto complete dropdown on activation of the control, rather than after User hits first key? private void loopsDataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { string[] paramStrings = { "OUT1", "OUT2" }; AutoCompleteStringCollection autoStrings = new AutoCompleteStringCollection(); autoStrings.AddRange(paramStrings); TextBox textbox = loopsDataGridView.EditingControl as TextBox; textbox.AutoCompleteCustomSource = autoStrings; textbox.AutoCompleteMode = AutoCompleteMode.SuggestAppend; textbox.AutoCompleteSource = AutoCompleteSource.CustomSource; }
Reply | Email | Modify 
waste of time by Przemek On July 18, 2009
As MVP you didn't make much effort to write this article. Did you?
Reply | Email | Modify 
Re: waste of time by Mahesh On May 24, 2010

Purpose of this article was to show how to use this new feature available in a ComboBox control. I am not sure what more effort you are looking for. This is all free world and whatever new I learn, I just share here. There is not much to it ;). Some people may find it useful who are new. Some people like yourself, who are advanced, may think this is a time waste.

Reply | Email | Modify 
Re: waste of time by thiru On March 18, 2011
hello sir its good to share here in so that beginners can learn u should not call it as time waste........if u have interest u can post r don't comment as waste on others articles
Reply | Email | Modify 
super coding by dinesh On March 21, 2010
super super super coding sir thanks lot sir
Reply | Email | Modify 
Re: super coding by Mahesh On May 24, 2010
Thank you Dinesh. Appreciate your kind words.
Reply | Email | Modify 
tnx by arthur On June 20, 2010
Tnx :)
Reply | Email | Modify 
autocomplete by Sirous On June 25, 2010
sir,
Is there a way to have the autocomplete feature in the middle of a sentence?
It works for the first word, but not after that.
Reply | Email | Modify 
Autocomplete by megha On July 26, 2010

Hi!!!
This is Megha, well i want to know is there any method via which we could change the font size of the autocomplete list.
I had tried changing the font size of the textbox this changes the font size of the text box but the list beneath it that matches the Autocomplete feature is of the smaller font only.
Reply | Email | Modify 
Between two textboxes? by Cheeyam On August 20, 2010
Hi,
I have two textboxes. As I type in one of them, there should be autosuggestion in the other one. Is this possible?

Thx
Reply | Email | Modify 
[WebMethod] by rajesh On September 15, 2010
[WebMethod]
    public string[] getClients(string prefixText, int count)
    {
        if (count == 0)
        {
            count = 10;
        }
        string key = prefixText + "%";

        string qry = "SELECT COUNT(id) FROM tb_123_clients WHERE client LIKE '" + key + "'";
        dr = dbu.executeReader(qry);
        if (dr.Read())
        {
            count = dr.GetInt32(0);
        }
        dr.Close();

        string[] items = new string[count];
        qry = "SELECT client FROM tb_123_clients WHERE client LIKE '" + key + "'";
        dr = dbu.executeReader(qry);
        int i = 0;
        while (dr.Read())
        {
            items.SetValue(dr["client"].ToString(), i);
            i++;
        }
        dr.Close();
        return items;

    }

Reply | Email | Modify 
auto complete textbox in wpf by Waqas On August 25, 2011
can u give the same functionality textbox in WPF ?????
Reply | Email | Modify 
excellent by Amol On September 8, 2011
nice to see such a amazing article...
Reply | Email | Modify 
Re: excellent by RASHEED On December 10, 2011
REALLY NICE. CAN WE AUTOCOMPLETE THE TEXTBOX FETCHING THE DATA FROM ACCESS DB IN WINDOWS APPLICATION USING C#. IF. PLS HELP ME.
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.