Click here to Skip to main content
6,596,602 members and growing! (22,537 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Intermediate

Auto complete text box using AJAX (Using Atlas)

By rperetz

How simple it is to have your won autocomplete text in asp.net 2.0
Windows, .NET, ASP.NET, Visual Studio, Dev
Posted:24 Jul 2006
Updated:1 Aug 2006
Views:133,526
Bookmarked:64 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
31 votes for this article.
Popularity: 6.24 Rating: 4.18 out of 5
2 votes, 6.5%
1
2 votes, 6.5%
2
1 vote, 3.2%
3
6 votes, 19.4%
4
20 votes, 64.5%
5

Introduction

In this article I will show how to build an auto complete text box from an ASP.net text box control. With the help of Atlas it's very easy to have your pages have AJAX abilities. here is a screen at 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 run on most modern browsers.

Step 1 - Get your next web site 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 step-by-step installation instructions 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:

    <%@ 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 text box. Now the the objective is to get this text box have Ajax abilites and make it a autocomplete text box, for that I would need to add a ScriptManager Atlas control

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

    The ScriptManager control is central to "Atlas". It manages all "Atlas" components on 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 Text box control is our AutoCompleteExtender control from Atlas:

    <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 the auto complete behavior, create a Web service containing a method with the following signature:

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

    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 autocompletion 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 Control our UI page should look like this:

    <%@ 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 DataLayer

    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 class:

    sqlHelper.cs - Microsoft Application Block for ADO.net
    SqlProductProvider.cs - our data provider, which has one method to return a sqldatareader

    Here is our function from the SqlProductProvider class:
    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 everytime the user will push a key therefore I decided to call a store procudure. Our Store Procedure is very simple, it take only one parameter and does a sql select with all the Product names that start with that parameter:

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

    Step 4 - Write our Web Service

    Let's have a look at the code:

    [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 use types in the text box, passing two values

    1. prefixText - the text he typed
    2. 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 the end I return the Array and that's all. Here is a screen shot that shows our autocomplete text box in action when you type the letter "c"

    Summary

    Let's review how all this works:
    we added Atlas control called AutoCompleteExtender this control talks to a webservice containing a method with this following signature:

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


    Each time the user typed in the text box, this Method will trigger passing the string the user typed, and the number of charcters. The next step is to write a query that runs with the given string, and return an array of string.

     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 generate JavaScript code for the AJAX and link to the text box we want to do the autocomplete. The great thing about all this, 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 all 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 have 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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

    A list of licenses authors might use can be found here

    About the Author

    rperetz


    Member
    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
    Occupation: Web Developer
    Company: TrafficTech
    Location: Canada Canada

    Other popular ASP.NET articles:

    Article Top
    You must Sign In to use this message board.
    FAQ FAQ 
     
    Noise Tolerance  Layout  Per page   
     Msgs 1 to 25 of 58 (Total in Forum: 58) (Refresh)FirstPrevNext
    GeneralAjaxControlToolkit PinmemberMember 78161020:24 3 Sep '08  
    GeneralRe: AjaxControlToolkit PinmemberTalha Ekram0:44 19 Mar '09  
    GeneralAtals is old Pinmemberrperetz5:24 3 Sep '08  
    Generalshould AutoCompleteExtender used only with webservice PinmemberMember 7816100:58 3 Sep '08  
    GeneralRe: should AutoCompleteExtender used only with webservice Pinmemberrperetz5:24 3 Sep '08  
    GeneralRe: should AutoCompleteExtender used only with webservice PinmemberMember 78161020:07 3 Sep '08  
    QuestionGet the code Pinmemberkollam20033:02 28 Jul '08  
    AnswerRe: Get the code Pinmemberrperetz5:25 3 Sep '08  
    QuestionMultiple auto complete PinmemberShariful Islam1:20 24 Jul '08  
    Questionauto suggest not working Pinmemberdhasu12310:03 10 Jun '08  
    QuestionAutoComplete TextBox Pinmemberrafiq_22jmr3:07 28 May '08  
    QuestionUsing page method instead of WEB SERVICE... PinmemberBobb198220:34 12 May '08  
    QuestionHow to change datasource PinmemberKasmax3:23 31 Oct '07  
    GeneralUsing AJAX PinmemberAdeel6882:42 3 Sep '07  
    GeneralRe: Using AJAX Pinmemberrperetz4:29 12 Sep '07  
    Questionissue with AutoCompleteExtender PinmemberRohit_Puranik21:40 26 Aug '07  
    GeneralYour Lecture is Awesome, However I insist add 1 Line... Pinmembercoverboy4:50 10 Jul '07  
    GeneralRe: Your Lecture is Awesome, However I insist add 1 Line... Pinmemberrperetz6:01 21 Aug '07  
    QuestionModifying AutoCompleteExtender to pass more parameter Pinmemberbrnskm6:45 27 Jun '07  
    GeneralCan I use this ? Pinmembersdklfjlkdsfjdklsfjkdslfjdslkf13:31 8 Apr '07  
    GeneralRe: Can I use this ? Pinmemberrperetz11:55 16 Apr '07  
    QuestionAtlas autocomplete in Multiple Column? Pinmembermungding6:02 12 Mar '07  
    GeneralAuto Complete Extender Pinmemberkvbasu23:43 25 Feb '07  
    GeneralAn easier and better alternative Pinmembernaits5:11 13 Feb '07  
    GeneralUsing a codebehind method inseat a webservice Pinmemberrm80003:57 18 Oct '06  

    General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

    PermaLink | Privacy | Terms of Use
    Last Updated: 1 Aug 2006
    Editor:
    Copyright 2006 by rperetz
    Everything else Copyright © CodeProject, 1999-2009
    Web13 | Advertise on the Code Project