Click here to Skip to main content
15,878,945 members
Articles / Web Development / ASP.NET

Auto complete text box using AJAX (Using Atlas)

Rate me:
Please Sign up or sign in to vote.
4.63/5 (36 votes)
1 Aug 2006CPOL7 min read 255.3K   1.6K   79   64
How simple it is to have your own auto-complete text in ASP.NET 2.0.

Introduction

In this article, I will show how to build an auto complete text box from an ASP.NET TextBox control. With the help of Atlas, it's very easy to have your pages have AJAX abilities. Here is a screenshot of the final product:

Background: What is Atlas

"Atlas" is a free framework for building a new generation of richer, more interactive, highly personalized cross-browser web applications. This new web development technology from Microsoft integrates cross-browser client-script libraries with the ASP.NET 2.0 server-based development framework. In addition, "Atlas" offers you the same type of development platform for client-based web pages that ASP.NET offers for server-based pages. And because "Atlas" is an extension of ASP.NET, it is fully integrated with server-based services. "Atlas" makes it possible to easily take advantage of AJAX techniques on the web, and enables you to create ASP.NET pages with a rich, responsive UI and server communication. However, "Atlas" isn't just for ASP.NET. You can take advantage of the rich client framework to easily build client-centric web applications that integrate with any backend data provider and runs on most modern browsers.

Step 1 - Get your next website be ready for Atlas

System requirements

  • Supported Operating Systems: Windows Server 2003; Windows XP.

Required software

  • Microsoft .NET Framework version 2.0
  • IE 5.01 or later: You must also be running Microsoft Internet Explorer 5.01 or later for all installations of the .NET Framework.

Optional software

  • Visual Studio 2005 or Visual Web Developer Express Edition (free download).

Install "Atlas" Setup - June CTP. This setup application installs the core "Atlas" files on your machine, and installs a Visual Studio 2005 web site template for creating your own "Atlas" application from a blank "Atlas" web project. If you have IIS installed, the setup can configure it to recognize file extensions used by "Atlas". You can find the latest Atlas framework at http://atlas.asp.net/default.aspx?tabid=47&subtabid=471. View the step-by-step installation instructions here. Once you have Atlas installed, you are ready to rock!

Step 2 - Create a new "Atlas" Web site

  • Start Visual Studio.
  • On the File menu, click New Web Site (Alternatively, click New, and then click Web Site).
  • Under My Templates, select ASP.NET 'Atlas Web Site'.
  • Select the location for your installation, select the language you want to use for the Web site, and enter or browse to the local path where you want to create the Web site: click OK.

When you create a new "Atlas" Web site, Visual Studio copies the "Atlas" run-time assembly from its installation location to the Web site's Bin folder. Visual Studio also generates a Web.config file that is preconfigured with settings required to run "Atlas" applications.

Step 3 - Let's do some AJAX baby!

First, we start with a very simple ASP.NET HTML page:

ASP.NET
<%@ Page Language="C#" AutoEventWireup="true" 
         CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
         "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</form>
</body>
</html>

As you can see, there is not much to know in this code. All I have here is a simple server-side ASP.NET TextBox. Now the objective is to get this text box have AJAX abilities and make it an auto-complete text box. For that, I would need to add a ScriptManager Atlas control.

ASP.NET
<atlas:ScriptManager ID="ScriptManager1" runat="server" />

The ScriptManager control is central to "Atlas". It manages all "Atlas" components in a page, handles partial page updates, and renders client scripts that enable you to access Web Service methods from JavaScript using proxy objects. The next thing we want to add under our TextBox control is our AutoCompleteExtender control from Atlas:

ASP.NET
<atlas:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server">

<atlas:AutoCompleteProperties Enabled="true"
  MinimumPrefixLength="1"
  TargetControlID="TextBox1"
  ServicePath="~/Services/ProductService.asmx"
  ServiceMethod="FindProducts" />
</atlas:AutoCompleteExtender>

What is AutoCompleteExtender?

The AutoCompleteBehavior component extends text box controls with auto-completion behavior, which sends the text that the user has entered to a Web Service method to obtain a list of suggestions for completing the text. The result is displayed in a drop-down panel underneath the text box. The user can use either the mouse or the keyboard to select one of the suggested strings.

To extend a text box with auto complete behavior, create a Web Service containing a method with the following signature:

C#
public string[] GetSuggestions(string prefixText, int count);

The prefixText parameter contains the text that the user has entered so far. The count parameter specifies the maximum number of possible values to return to the client. The method returns an array of strings that are displayed one to a line in the drop-down panel. No drop-down panel appears if the result is empty or if the Web Service does not return a result at all. The method name is determined by the ServiceMethod property, and can be any valid C# identifier. The parameter names must match the ones used in the method signature above. Once you have a Web Service that retrieves a list of suggestions, you can add an AutoCompleteBehavior component to the behaviors element of a TextBox control. At a minimum, you must set the serviceURL and serviceMethod properties, to specify the Web Service used to obtain suggestions. Several other properties exist, to fine-tune the behavior of auto-completion lists, including completionInterval to specify how frequently the suggestions get updated, completionSetCount to limit the number of suggestions returned, and minimumPrefixLength to set the minimum number of characters the user must enter before any suggestions are shown. After adding these two Atlas controls, our UI page should look like this:

ASP.NET
<%@ Page Language="C#" AutoEventWireup="true" 
         CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" 
              "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<atlas:ScriptManager ID="ScriptManager1" runat="server" />
<div>
</div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<atlas:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server">
<atlas:AutoCompleteProperties Enabled="true"
    MinimumPrefixLength="1"
    TargetControlID="TextBox1"
    ServicePath="~/Services/ProductService.asmx"
    ServiceMethod="FindProducts" />
</atlas:AutoCompleteExtender> 
</form>
</body>
</html>

Step 3 - Write our Data Layer

With the help of Microsoft Data Access Application Block for .NET, I created a very simple and useful data layer (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag2/html/daab.asp). Note: I have included all the code in the download sample. I have two classes:

  • sqlHelper - Microsoft Application Block for ADO.NET.
  • SqlProductProvider - our data provider, which has a method to return a SqlDataReader.

Here is our function from the SqlProductProvider class:

C#
public static SqlDataReader GetProductLists(String owner)
{
    SqlDataReader reader = SqlHelper.ExecuteReader(ConnectionString, 
                               "GetProjectLists", owner);
    return reader;
}

Our Web Service will call this function, to get all the records that start with a given string (the string that you type in your text box). I know that this function will be called every time the user will push a key; therefore, I decided to call a Stored Procedure. Our Stored Procedure is very simple; it takes only one parameter and does a SQL Select with all the product names that start with that parameter:

SQL
SELECT
    ProductName
FROM
    Products
WHERE
    ProductName like @pProductName +'%'

Step 4 - Write our Web Service

Let's have a look at the code:

C#
[WebMethod]
public String[] FindProducts(String prefixText, int count)
{
    //return all records whose Title starts with the prefix input string
    List<STRING> titleArList = new List<STRING>();

    SqlDataReader drProducts = sqlProductProvider.GetProductLists(prefixText);

    while (drProducts.Read())
    {
        String strTemp = Convert.ToString(drProducts["ProductName"]);
        titleArList.Add(strTemp);
    }
    return titleArList.ToArray();
}

The WebMethod FindProducts will be called each time the usee types in the text box, passing two values:

  • prefixText - the text typed
  • count - number of characters (for example, 2 characters for "IV")

In this function, I loop my dataReader and add the results to an array. And in the end, I return the array and that's all. Here is a screenshot that shows our auto-complete text box in action when you type the letter "c".

Summary

Let's review how all this works: we added an Atlas control called AutoCompleteExtender. This control talks to a Web Service containing a method with the following signature:

C#
public string[] GetSuggestions(string prefixText, int count);

Each time the user types in the text box, this method will be triggered, passing the string the user typed and the number of characters. The next step is to write a query that runs with the given string and returns an array of strings:

C#
SqlDataReader drProducts = sqlProductProvider.GetProductLists(prefixText);

while (drProducts.Read())
{
    String strTemp = Convert.ToString(drProducts["ProductName"]);
    titleArList.Add(strTemp);
}
return titleArList.ToArray();

Now the AutoCompleteExtender control does the rest; it generates the JavaScript code for the AJAX and links to the text box we want to do the auto-complete for. The great thing about all this is my text box is still an ASP Server control, so I still have all the power in the code-behind to do whatever I want with a rich UI.

Try my code

Here are the steps to run my code:

  1. Download the zip file.
  2. Copy the folder "AtlasTextBoxAutoComplete" to your web site folder (C:\Documents and Settings\[your name]\My Documents\Visual Studio 2005\WebSites).
  3. Open VS2005 and create a new C# web site called "AtlasTextBoxAutoComplete" (don't need to select the Atlas template since my site already has all the Atlas DLLs), and point the site to the location you saved your folder (C:\Documents and Settings\[your name]\My Documents\Visual Studio 2005\WebSites\AtlasTextBoxAutoComplete).
  4. VS2005 will give you a message saying "Web Site already exists". Now, you select "Open the existing web site", and push OK.
  5. Click on default.aspx (to make it your start up page) and run.
  6. Type the letter "c" and wait 3 seconds... and see the magic. (The look up is on the Product Table on Product Name.)

Feedback

Feel free to leave any feedback on this article; it's my first one, so go easy on me.

License

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


Written By
Web Developer TrafficTech
Canada Canada
Have technical skills that can be demonstrated and an ability to resolve complex problems quickly while working in a demanding, high pressure environment

Designs, plans, and coordinates software development work teams

Provides technical mentorship to project team members

Handles complex application features and technical designs for the development of new applications.

Write articles about ASP.net:
http://www.codeproject.com/KB/aspnet/SQLHelper20.aspx http://www.codeproject.com/KB/aspnet/DateAndTimePicker.aspx http://www.codeproject.com/KB/aspnet/SQLHelper20.aspx http://www.codeproject.com/KB/aspnet/WaitImageBoxWhilePagePost.aspx

Designs and implements the components, frameworks and layers required for complex application features

Understands and participate in all aspects of the Software Development Life Cycle

Relies on experience and judgment to plan and accomplish goals.

Ability to perform various programming activities (coding, testing, debugging, documenting, maintaining and supporting).

Ability to work independently with minimal supervision.

10 years’ experience in web software design and development.

SpecialtiesASP.net
SQL 2005
AJAX 1.0
Linq
C# 3.5
Microsoft Application Blocks
Java Script
Reporting Services
SQL SSIS
XML
Classic ASP

Comments and Discussions

 
GeneralNeed ASP version of Auto complete script Pin
maddy4in20-Jun-10 0:47
maddy4in20-Jun-10 0:47 
GeneralRe: Need ASP version of Auto complete script Pin
rperetz12-Aug-10 12:34
rperetz12-Aug-10 12:34 
GeneralRe: Need ASP version of Auto complete script Pin
rperetz20-May-11 3:47
rperetz20-May-11 3:47 
GeneralAjaxControlToolkit Pin
Member 7816103-Sep-08 19:24
Member 7816103-Sep-08 19:24 
GeneralRe: AjaxControlToolkit Pin
Talha Ekram18-Mar-09 23:44
Talha Ekram18-Mar-09 23:44 
GeneralRe: AjaxControlToolkit Pin
rperetz28-Jan-10 9:53
rperetz28-Jan-10 9:53 
GeneralAtals is old Pin
rperetz3-Sep-08 4:24
rperetz3-Sep-08 4:24 
Generalshould AutoCompleteExtender used only with webservice Pin
Member 7816102-Sep-08 23:58
Member 7816102-Sep-08 23:58 
GeneralRe: should AutoCompleteExtender used only with webservice Pin
rperetz3-Sep-08 4:24
rperetz3-Sep-08 4:24 
GeneralRe: should AutoCompleteExtender used only with webservice Pin
Member 7816103-Sep-08 19:07
Member 7816103-Sep-08 19:07 
QuestionGet the code Pin
member 104177028-Jul-08 2:02
member 104177028-Jul-08 2:02 
AnswerRe: Get the code Pin
rperetz3-Sep-08 4:25
rperetz3-Sep-08 4:25 
QuestionMultiple auto complete Pin
Shariful Islam24-Jul-08 0:20
Shariful Islam24-Jul-08 0:20 
Questionauto suggest not working Pin
dhasu12310-Jun-08 9:03
dhasu12310-Jun-08 9:03 
Hi rperetz - Installation was super easy. But when i type in a letter(s) nothing happens. Not sure what hapenned here. I am using vs 2005 and .net 2.0

Also is there a vb version that you have for this code. Thanks
QuestionAutoComplete TextBox Pin
rafiq_22jmr28-May-08 2:07
rafiq_22jmr28-May-08 2:07 
QuestionUsing page method instead of WEB SERVICE... Pin
Bobb198212-May-08 19:34
Bobb198212-May-08 19:34 
QuestionHow to change datasource Pin
Kasmax31-Oct-07 2:23
Kasmax31-Oct-07 2:23 
GeneralUsing AJAX Pin
Adeel6883-Sep-07 1:42
Adeel6883-Sep-07 1:42 
GeneralRe: Using AJAX Pin
rperetz12-Sep-07 3:29
rperetz12-Sep-07 3:29 
Questionissue with AutoCompleteExtender Pin
Rohit_Puranik26-Aug-07 20:40
Rohit_Puranik26-Aug-07 20:40 
GeneralYour Lecture is Awesome, However I insist add 1 Line... Pin
User 299712410-Jul-07 3:50
User 299712410-Jul-07 3:50 
GeneralRe: Your Lecture is Awesome, However I insist add 1 Line... Pin
rperetz21-Aug-07 5:01
rperetz21-Aug-07 5:01 
QuestionModifying AutoCompleteExtender to pass more parameter Pin
brnskm27-Jun-07 5:45
brnskm27-Jun-07 5:45 
AnswerRe: Modifying AutoCompleteExtender to pass more parameter Pin
SaramMalik25-Jan-10 6:57
SaramMalik25-Jan-10 6:57 
GeneralRe: Modifying AutoCompleteExtender to pass more parameter Pin
rperetz26-Jan-10 17:01
rperetz26-Jan-10 17:01 

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

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