Click here to Skip to main content
Email Password   helpLost your password?

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.

  • You must Sign In to use this message board.
     
     
    Per page   
     FirstPrevNext
    GeneralAjaxControlToolkit
    Member 781610
    20:24 3 Sep '08  
    Hi,

    Where can i get this ?

    Is it a installation exe some thing like MS .Net FrameWork 2.0.

    I downloaded one by the name AjaxControlToolkit.zip and once when i unzipped it i ran
    \AjaxControlToolkit\AjaxControlExtender\AjaxControlExtender.vsi and it started to ask for installing .cs and. vb files.

    I created a project and included some of the files and when compiled i got

    The type or namespace name 'AjaxControlToolkit' could not be found (are you missing a using directive or an assembly reference?)
    from a file called CombineScriptsHandler.ashx.
    Should i need to reference some dll files.

    I need this desperatly as i have to start learning ajax and start my project in another 3 days.

    Plz Help Smile


    Regards,

    Sree

    Long Live

    GeneralRe: AjaxControlToolkit
    Talha Ekram
    0:44 19 Mar '09  
    Download the latest version, this problem got resolved in AjaxControlToolkit version 2.0 and above. Big Grin

    Talha Rulz

    GeneralRe: AjaxControlToolkit
    rperetz
    10:53 28 Jan '10  
    Read this
    http://forums.asp.net/t/1155780.aspx[^]
    GeneralAtals is old
    rperetz
    5:24 3 Sep '08  
    Hi thanks for all the feedback, let me just note that Atlas is old now.
    and ASP.net 2.0 has new controls with Ajax.
    Please view this page for doing autocomplete http://www.asp.net/AJAX/AjaxControlToolkit/Samples/AutoComplete/AutoComplete.aspx[^]

    you can still use my idea for doing it from a database.
    Generalshould AutoCompleteExtender used only with webservice
    Member 781610
    0:58 3 Sep '08  
    Hi,

    I'm a newbie for ajax. I've come across samples for AutoCompleteExtender implementing only webservice for the source of their data.

    Is it possible to use an ordinary function to get the data loaded into the text box.

    for example,

    can i use the AutoCompleteExtender to a method M() in my asp.net application to return data.

    I need it urgently.Frown
    can any one clarify me this.

    Thanks and Regards

    Sree

    Long Live

    GeneralRe: should AutoCompleteExtender used only with webservice
    rperetz
    5:24 3 Sep '08  
    Yes, it has to be a web service method, all you have to do is say [WebMethod] on the top of the function no bigy
    GeneralRe: should AutoCompleteExtender used only with webservice
    Member 781610
    20:07 3 Sep '08  
    Hi,

    Thanks Smile

    Sree

    Long Live

    QuestionGet the code
    kollam2003
    3:02 28 Jul '08  
    how to capture the code, in the text box with project name and hidden control store the code, how can achive this. please guide me. thanks

    deepak

    AnswerRe: Get the code
    rperetz
    5:25 3 Sep '08  
    there is a link to download the code.
    QuestionMultiple auto complete
    Shariful Islam
    1:20 24 Jul '08  
    Hi,
    i need auto complete feature in a textbox. it's a address box for an e-mail sending webpage.
    so it should work multiple time. forexample; first i write an e-mail Id starting with 'a' so it should
    get all the emailid that starts with 'a'. then i write a semicolon(;) and want to write another email id . how can i provide this auto complete feauture. it would be realy helpfull for me if u give me a solution.

    sharif
    Questionauto suggest not working
    dhasu123
    10:03 10 Jun '08  
    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
    rafiq_22jmr
    3:07 28 May '08  
    Confused

    Hai Developers i have one Problem.
    If i enter one character in textbox(HTML means input type="text")that character's corresponding all data(from database) will come dropdown.
    i need some coding help.If it is possible to do in Jsp.

    in this link they used Ajax:http://www.codeproject.com/KB/aspnet/Autocomplete.aspx[^]
    i need it in jsp
    Help me
    Thank u


    Rafiq
    QuestionUsing page method instead of WEB SERVICE...
    Bobb1982
    20:34 12 May '08  
    Hello everybody...

    I was trying to create this autocomplete textbox thing but without using a WebService. Read some where while googling that it can be achieved by setting up some properties. M not getting any error but m not even getting any suggetions. Please help me...m putting my code here.

    ASPX Page...

    &lt;%@ Page Language="C#" AutoEventWireup="true" CodeFile="AutoComplete.aspx.cs" Inherits="AutoComplete" %&gt;

    &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

    &lt;html xmlns="http://www.w3.org/1999/xhtml" &gt;
    &lt;head runat="server"&gt;
          &lt;title&gt;Untitled Page&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
          &lt;form id="form1" runat="server"&gt;
          &lt;div&gt;
                &lt;asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server"&gt;
                &lt;/asp:ScriptManager&gt;
                &lt;ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"  
                TargetControlID="TextBox1" MinimumPrefixLength="1" ServicePath="AutoComplete.aspx" ServiceMethod="GetAllNames"&gt;
                &lt;/ajaxToolkit:AutoCompleteExtender&gt;
                &lt;br /&gt;
         
          &lt;/div&gt;
                &lt;asp:TextBox ID="TextBox1" runat="server" Width="255px" Height="15px"&gt;&lt;/asp:TextBox&gt;
          &lt;/form&gt;
    &lt;/body&gt;
    &lt;/html&gt;

    ---------------------------------------------------
    ASPX.CS Page...


    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Web.Services;
    using System.Data.OleDb;
    using System.Web.Script.Services;


    public partial class AutoComplete : System.Web.UI.Page
    {
          protected void Page_Load(object sender, EventArgs e)
          {
            
          }
      
          public static string[] GetAllNames(string prefixText, int count)
          {
                string strCon;
                string strSQL = "select s_firstName from iWebOne_M_User where s_firstName like '%" + prefixText + "%'";
                strCon = ""; //Sorry guys cant show the connection string part..security issue
                OleDbConnection objCon = new OleDbConnection(strCon);
                objCon.Open();
                OleDbCommand objCom = new OleDbCommand(strSQL, objCon);
                OleDbDataReader objReader = objCom.ExecuteReader();
                //string[] names;

                ArrayList filteredList = new ArrayList();
                while (objReader.Read())
                {
                      filteredList.Add(objReader["s_firstName"]);
                }
                objReader.Close();
                return (string[])filteredList.ToArray(typeof(string));
          }
    }


    Please help me....

    Thanks in advance.. Smile
    Bobbie
    QuestionHow to change datasource
    Kasmax
    3:23 31 Oct '07  
    I am trying to use it and reading the Tutorial. i cant figure out how to change the data source. for example i want to use my our database and table field instead of ProductName field of Northwing table.
    can someone plz tell me where to make changes?

    thanks

    GeneralUsing AJAX
    Adeel688
    2:42 3 Sep '07  
    Atlas is outdated, I want to achieve the same using AJAX, how can I do that??

    Thanks in Advance
    GeneralRe: Using AJAX
    rperetz
    4:29 12 Sep '07  
    Yes I know it's called Ajax 1.0 (or 2.0) I am not sure which one is the last one
    I am sure it's just the name tag is diffrent, but the rest should be the same.
    I will build one, and write a new article when I finsh.
    Questionissue with AutoCompleteExtender
    Rohit_Puranik
    21:40 26 Aug '07  
    hi,
    i am facing an issue with AutoCompleteExtender control. Let me explain the scenario first, I am having AutoCompleteExtender control on one of a web page of my project. When i debug (Run) this project in Visual Studio 2005, the AutoCompleteExtender control works fine. Smile
    Now, I've also created the virtual directory of this project using IIS on my machine. But the issue here is that when i access my project through this virtual directory, the AutoCompleteExtender control doesn't work Cry (i mean, when i type into the TextBox, it doesn't displays me the list of matching records). It also doesn't show any error...Confused
    Can anyone explain me why this happens so...Sigh and what shall i do to get my AutoCompleteExtender working...???
    if any one knows how to fix this problem, please e-mail me the solution. My e-mail id is : mail.abhijeet@hotmail.com
    it's very very urgent for me guys...please help...

    Thank u in advance...Smile

    Love,
    -Abhijeet

    GeneralYour Lecture is Awesome, However I insist add 1 Line...
    coverboy
    4:50 10 Jul '07  
    Hi...rperetz...

    I adopted your lecture to my site ( http://www.gangsanhae.net )

    Located anyPage top-center Search (Category : total...pension, company)

    And, I encountered Connection pooling Problem.

    Because, Closing Connection was not in your source...

    I didn't predict AJAX Search dramitically increase connection pool.

    So, I insist you to add Just 1 Line to your source.

    SqlDataReader drProducts = sqlProductProvider.GetProductLists(prefixText);

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

    drProducts.Close();
    return titleArList.ToArray();

    And, Great Thanks to you and your lecture.
    GeneralRe: Your Lecture is Awesome, However I insist add 1 Line...
    rperetz
    6:01 21 Aug '07  
    you are right, data reader keep the connection open.
    now thinking about it, I think using datatable would be a much better way.

    thanks for your input
    QuestionModifying AutoCompleteExtender to pass more parameter
    brnskm
    6:45 27 Jun '07  
    Great Article! I implemented my AutoCompleteExtender by writing out the entire SQL SELECT statement in WebService and now I need to further enhance my SELECT query. Basically, I need to make my SELECT statement dynamic depending on the parameter passed from the code page to the WebService.

    Has anyone been able to modify Microsoft's AutoCompleteExtender javascript to pass more parameters?

    Thanks.
    AnswerRe: Modifying AutoCompleteExtender to pass more parameter
    SaramMalik
    7:57 25 Jan '10  
    Hi,

    I also need that AutoCompleteExtender with more parameter. Actually i need to get the cities in the auto-complete that i have done, but now i need to filter the cities by Country.

    Please help

    Saram

    GeneralRe: Modifying AutoCompleteExtender to pass more parameter
    rperetz
    18:01 26 Jan '10  
    You can do it, the code is my office.
    once I get there I will update this thread. In fact I thinking to writing an second article on autocomplete with Ajax 2.0 (Atlas is too old now).
    Ronnie
    GeneralCan I use this ?
    sdklfjlkdsfjdklsfjkdslfjdslkf
    13:31 8 Apr '07  
    Hi.

    Theese two classes, sqlHelper.cs and sqlProvider.cs, can I use them in my own project ?
    ( it's a project I am having at my school, and I have big time trouble with getting data from database into a textbox. Do yo know about other examples as well ? )

    Best regards.

    GeneralRe: Can I use this ?
    rperetz
    11:55 16 Apr '07  
    If these two classes will give you joy and happnies...then go for it.
    you may want to download job Starter kit from the asp.net site, it has more example of data access (easy).

    ho yes, I love your name

    Ronnie
    QuestionAtlas autocomplete in Multiple Column?
    mungding
    6:02 12 Mar '07  
    how do i atlas textbox in multi Column ?please?Sigh


    Last Updated 1 Aug 2006 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010