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

Simplify data entry with AutoComplete

, 15 Jan 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
A tutorial demonstrating the power of the AutoComplete feature of the TextBox control using a Windows Forms client and SQL Server 2000 data.

Overview

This is a tutorial demonstrating the power of the AutoComplete feature of the TextBox control using a Windows Forms client and SQL Server 2000 data.

Sample screenshot

Figure 1 – Example in run-time mode

Introduction

If you ask any end-user what is that most desired feature they look for in software application, I bet the most common answer would be “must be easy to use”. There are many different ways in which we can improve the end-user experience. In this article, I’ll demonstrate to you how a simple AutoComplete feature for the TextBox control can greatly enhance data entry.

I assume the reader has a basic understanding of the Visual Studio 2005 IDE and is comfortable writing code using C#. Since this tutorial uses 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 website 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—just select AutoComplete's match and go!

Say you've recently visited the website 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 website, AutoComplete will present you with a list of places you've been on that site.

Well, it works with Internet Explorer. However, I wanted to see the same done in my accounting application. If I type data inside the Customer ID textbox, will I be able to see a list of all the customers in the system?

Sure I can, with the help of the new functionality built into the TextBox control; the developer can design applications which can have the AutoComplete feature. Here is the deal, if you want to be treated like a super hero by your end-users, then you go ahead 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 you don’t have to remember 2000+ customer IDs anymore).

Let’s create a Windows Application Project

If VS 2005 IDE is not already started, then you can launch the IDE by clicking on the Windows Start button -> All Programs -> Microsoft Visual Studio 2005 -> click on icon Microsoft Visual Studio 2005. You may have others ways to lunch the IDE, such as clicking on a shortcut on your desktop and so on.

Please do the following steps to create a Windows Application Project:

  • Click on menu File -> New -> Project… or you can press the hot key Ctrl + Shift + N (please see Figure 2).
  • From the New Project dialog box, select Visual C# -> Windows.
  • From Templates, select Windows Application.
  • Please give a name to the application. I’ve called the project “WinAutoComplete”. You may choose a different location for storing the application files as per your preference. Please see Figure 3 for an illustration of the naming process.
  • Click on the OK button to finish the process. VS 2005 will create a new project, and your project should look like Figure 4.

Sample screenshot

Figure 2 – Process to create New Windows Application Project

Sample screenshot

Figure 3 – Project selection and naming process

Sample screenshot

Figure 4 – View of newly created project

As such, most of you’ll see something similar to what Figure 4 looks like; however, depending on your current VS 2005 IDE settings, you might see some toolbox hidden or floating. In any case, you should see the blank Form1 created for you as a result of the new project. Please refer to VS2005 Help to customize the look and feel of the IDE.

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

Let’s set properties of Form1 as per Table 1 to make sure the look and feel is good enough for our end-users to provide input (if any) and view the report. In case the property tool box is not visible in the IDE, you may hit F4 key to make it visible. Please make sure to select Form1 before applying changes to the properties using the properties toolbox.

Table 1. Properties of Form1
Property Value
Text Windows Forms AutoComplete Example
Size 375, 200

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

Time to add some controls to the newly created Form1

This is how the example looks like: I’ll create a sample application which lets the user type the product ID from the NorthWind database of SQL Server 2000. AutoComplete works in a different pattern; I’ll make sure the user tries a different pattern and see which one works better for them.

We need the following controls on Form1:

  • ComboBox with a different pattern of AutoComplete
  • Three Labels (Pattern Type, Product ID, and File System)
  • Two TextBoxes (Product ID and File System)

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

Sample screenshot

Figure 5 – Form1 designer surface after adding controls

Please change the properties of controls as per Table 2:

Table 2. Properties setup of controls on Form1

Report Item Property Value
Label1 Text Pattern Type
Label2 Text Product ID
Label3 Text File System
comboBoxPattern Collection Suggest, Append, SuggestAppend
comboBoxPattern DropDownStyle DropDownList
txtFileSystem AutoCompleteMode SuggestAppend
txtFileSystem AutoCompleteSource FileSystem

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 selected index changed event of comboBoxPattern. Please make sure your code looks like:

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!

Hurry! We’re done with all the hard work, it is time to reap the fruit. Let’s build the project and see if your project looks the same as shown in Figure 1. So fingers crossed? And ready to hit F5 on your keyboard?

I assume at this moment that your code has no compile level error which will prevent the build from happening. Now go ahead and check how the result looks like. To me, I can only imagine two typical scenarios: either you’ll be throwing your hands in the air and yelling yes, or a silent whisper, oops.

In both cases, I’m with you. If you said yes, then congratulations, you’ve done it. This is just the beginning, soon you’ll find yourself cracking heck of cool AutoComplete enabled data entry controls. Now, if you said oops, then nothing to panic, just make sure you have done all the steps. In case of a major issue, just start from scratch.

Append

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

Sample screenshot

Figure 6 – Example of Append Pattern

Suggest

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

Sample screenshot

Figure 7 – Example of Suggest Pattern

SuggestAppend

The SuggestAppend pattern is a combination of both Suggest and Append. Please see 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 user experience. Apart from providing a custom source, you can see that in-built AutoComplete features like a file system is also handy to help the data entry to be done easily.

Thank you for reading; I sincerely hope this article will help you a bit or two to know about user interface enhancements. Feel free to drop me a line with your comments/suggestion at asif.blog@gmail.com.

License

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

Share

About the Author

Asif Sayed
Architect FeatherSoft Inc.
Canada Canada
Asif Sayed has over twenty + years experience in software development and business process architecture. He has a consulting firm in Toronto, Canada. His firm provides IT solutions to all sizes of industries. He also teaches .NET technologies at Centennial College in Scarborough, Ontario. Recently he has become member of team as a subject matter experts with Microsoft's Learning Division. He has a book published by Apress with the Title "Client-Side Reporting with Visual Studio in C#".
 
My blog: http://www.dotnetsme.com
My Website: http://www.feathersoft.ca
Follow on   Twitter

Comments and Discussions

 
General[My vote of 1] Extremely Simple Example PinmemberNetDefender28-Nov-09 2:35 
GeneralRe: [My vote of 1] Extremely Simple Example PinmemberAsif Sayed28-Nov-09 5:04 
QuestionHow to fire AutoComplete in TextBox without enter any text? Pinmember8kelvin14-Mar-09 19:15 
GeneralMultiline textbox PinmemberPosiRob10-Feb-09 5:54 
GeneralRe: Multiline textbox Pinmemberjabit22-Dec-09 4:44 
GeneralRe: Multiline textbox PinmemberPosiRob25-Dec-09 4:42 
Questionreturn character problem PinmemberKarl 200024-Mar-07 7:04 
GeneralData Binding PinmemberElliott Keith23-Jan-07 18:38 
GeneralRe: Data Binding PinmemberAsif Sayed24-Jan-07 0:13 
GeneralSimplify it even more if only ... PinmemberGlen Harvy15-Jan-07 19:03 
GeneralRe: Simplify it even more if only ... PinmemberAsif Sayed16-Jan-07 11:29 
GeneralRe: Simplify it even more if only ... [modified] PinmemberGlen Harvy16-Jan-07 11:46 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.1411023.1 | Last Updated 15 Jan 2007
Article Copyright 2007 by Asif Sayed
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid