Simplify Data Entry with AutoComplete

A Tutorial Demonstrating the Power of the AutoComplete Feature of the TextBox Control Using Windows Forms Client and SQL Server 2000 Data

Asif Sayed

October 30, 2009

8 Min Read
ITPro Today logo

If you ask any end user what is the most desired feature they look for in a software application, I bet the most common answer is, it must be easy to use . There are many ways one can improve the end-user experience. In this article I ll demonstrate how a simple AutoComplete feature of the TextBox control can greatly enhance data entry (see Figure 1).

I assume the reader has a basic understanding of the Visual Studio 2005 IDE and is comfortable with writing the code using C#. Because this tutorial is using data stored inside SQL Server, a basic understanding of SQL statements and data connectivity is desirable.

What Is AutoComplete?

It is always a good thing to learn with the help of an example; Internet Explorer includes a feature called AutoComplete that keeps track of information that you ve recently typed, such as Web site addresses, information in forms, and search queries. As you type new information, AutoComplete tries to anticipate what you are typing and offers possible matches. You save time because you don t have to type in the full information simply select AutoComplete s match and go!

Say you ve recently visited the Web site http://www.ebay.com and you want to go back. You can type 'http://www.eb' or even just eb and AutoComplete will fill in the rest of the Web address for you. If you ve visited more than one place on a Web site, AutoComplete will present you with a list of places you ve been on that site.

So, it works with Internet Explorer. However, I wanted to see if the same can be done with my Accounting Application. If I type data inside a Customer ID TextBox, will I be able to see a list of all the customers in the system.

You bet! With the help of new functionality built into the TextBox control, a developer can design an application that can have the AutoComplete feature. Here s the deal if you want to be treated like a superhero by your end users, put this feature in your application and enjoy the fame (trust me on this, I already have three promissory notes of parties from one of my overseas clients; imagine if one need not remember 2,000+ customer IDs anymore).

Let s Create a Windows Application Project

If the Visual Studio 2005 IDE is not already started, you can launch the IDE by selecting Start | Programs | Microsoft Visual Studio 2005. (You may have other ways to launch the IDE, such as clicking it on your desktop, and so on.)

Follow these steps to create a Windows Application Project:

  • Select File | New | Project or press Ctrl+Shift+N (see Figure 2).

  • From the New Project dialog box select Visual C# | Windows.

  • From Templates select Windows Application.

  • Name the application; I ve named the project WinAutoComplete . You may choose a different location for storing the application files, as per your preference (see Figure 3).

  • Click the OK button to finish the process. VS 2005 will create a new project; more or less your project should look like Figure 4.

As such, most of you will see something similar to that shown in Figure 4; however, it depends on your current VS 2005 IDE settings. In any case, you should see the blank Form1 created for you as a result of a new project. Please refer to VS 2005 help to customize the look and feel of the IDE.

Tip: You can always access the menu by selecting View | Toolbox or Ctrl+Alt+X to make the Toolbox window visible if it is hidden or you don t see it in the IDE. To get the maximum space on the designer surface, you may like to use the Auto Hide feature of Toolboxes.

Let s set the properties of Form1 as per the table shown below, to make sure the look and feel is good enough for our end users to provide input (if any) and view the report. If the Property toolbox is not visible in the IDE, hit F4 to make it visible. Please make sure to select Form1 before applying changes to properties using the Property toolbox.

Property

Properties of Form 1

Text

Size

Note: When a new project is created, a solution also gets created with it. You may have one or more projects inside one solution.

Time to Add Some Controls to Our Newly Created Form1

Let s create a sample application that lets the user type the Product ID from the Northwind Database of SQL Server 2000. AutoComplete works in different patterns; I ll provide different patterns to see which one works best for users.

We need the following controls on Form1:

  • A ComboBox with a different pattern of AutoComplete

  • Three Labels (Pattern Type, Product ID, and File System)

  • Two TextBoxs (Product ID and File System)

Let s start by dragging and dropping the above mentioned controls on the Form1. Make sure your Form1 looks something similar to Figure 5.

Change the properties of the controls, as per the following table:

Report Item

Properties Setup of Controls on Form 1

Label1

Label2

Label3

comboBoxPattern

comboBoxPattern

txtFileSystem

txtFileSystem

Let s Write Some C# Code to Bring Life to Form1

The bulk of the code is written inside the Load event of Form1. The instruction to define which pattern must be applied is written inside the SelectedIndexChanged event of comboBoxPattern. Your code should look like this:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Data.SqlClient;using System.Collections;namespace WinAutoComplete{   public partial class Form1 : Form   {       AutoCompleteStringCollection ProductList = new           AutoCompleteStringCollection();       public Form1()       {           InitializeComponent();       }       private void Form1_Load(object sender, EventArgs e)       {           //declare connection string           string cnString = @"Data Source=(local); Initial Catalog=northwind;" +                   "User Id=northwind;Password=northwind";           /*use following if you use standard security           string cnString = @"Data Source=(local);Initial           Catalog=northwind; Integrated Security=SSPI"; */           //declare Connection, command and other related objects           SqlConnection conGetData = new SqlConnection(cnString);           SqlCommand cmdGetData = new SqlCommand();           SqlDataReader drGetData;           try           {               //open connection               conGetData.Open();               //prepare connection object to get the data through               //reader and populate into dataset               cmdGetData.CommandType = CommandType.Text;               cmdGetData.Connection = conGetData;               cmdGetData.CommandText = "Select ProductName From Products";               //read data from command object               drGetData = cmdGetData.ExecuteReader();               if (drGetData.HasRows == true)               {                   while (drGetData.Read())                       ProductList.Add(drGetData["ProductName"].ToString());               }               else                   MessageBox.Show("No data found in Products tables");               //close reader and connection               drGetData.Close();               conGetData.Close();               //set the default pattern to SuggestAppend               comboBoxPattern.SelectedIndex = 2;               txtProductID.AutoCompleteMode = AutoCompleteMode.SuggestAppend;               txtProductID.AutoCompleteSource = AutoCompleteSource.CustomSource;               txtProductID.AutoCompleteCustomSource = ProductList;           }           catch (Exception ex)           {               MessageBox.Show(ex.Message);           }           finally            {               //check if connection is still open then attempt to close it               if (conGetData.State == ConnectionState.Open)               {                   conGetData.Close();               }           }       }       private void comboBoxPattern_SelectedIndexChanged(object sender, EventArgs e)       {           switch (comboBoxPattern.Text)           {               case "Suggest":                   txtProductID.AutoCompleteMode = AutoCompleteMode.Suggest;                   break;               case "Append":                   txtProductID.AutoCompleteMode = AutoCompleteMode.Append;                   break;               case "SuggestAppend":                   txtProductID.AutoCompleteMode = AutoCompleteMode.SuggestAppend;                   break;           }       }  }}

Let the Show Begin!

Hurray! Now that we re done with all the hard work, it s time to reap the fruit. Let s build the project and see if your project looks similar to that shown in Figure 1. Fingers crossed? Ready to hit F5 on your keyboard?

I assume at this moment that your code has no compile-level error that will prevent the build to happen. Now, check the results. I can imagine two typical scenarios; either you ll be throwing your hands in the air and yelling YES , or silently whispering, oops .

In either case, I m with you. If you said YES, then congratulation, you ve done it. This is just the beginning; soon you ll find yourself cracking cool AutoComplete-enabled data-entry controls. If you said oops, don t panic, simply make sure you ve done all the steps. In case of a major issue, start over from scratch.

Append

If we use this pattern of AutoComplete, end users will see the suggested entry appended as each key is pressed. For example, if you type to you ll get tofu . See Figure 6 for an example of the Append pattern.

Suggest

If we use this pattern of AutoComplete, end users will see the suggested entry displayed with the choices narrowed down as each key is pressed. However, the Product ID field will not be appended. For example, if you type to you won t get tofu appended to the Product ID textbox. See Figure 7 for an example of the Suggest pattern.

SuggestAppend

The SuggestAppend pattern is a combination of Suggest and Append. Look back at Figure 1 for an example of this pattern.

Conclusion

As you can see, a simple feature like this can go a long way to win the trust of your end users and improve the user experience.

Thank you for reading; I hope this article helps you. Feel free to drop me a line with your comments/suggestion at [email protected].

Asif Sayed has more than 15 years of experience in software development and business process architecture. A senior systems analyst with Direct Energy in Toronto, Canada, he also teaches .NET technologies at Centennial College in Scarborough, Ontario. He is currently writing a book for Apress about Local Mode Reporting Services Using Visual Studio 2005, which is going to press at the end of May 2007.

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like