Sunday, January 29, 2012

Creating a Simple Auto-Complete TextBox with ASP.Net Ajax

AutoComplete is an ASP.NET AJAX extender that can be attached to any TextBox control, and will associate that control with a popup panel to display words that begin with the prefix typed into the textbox. The dropdown with your words supplied by a web service is positioned on the bottom left of the text box.
When you have typed more content than the specified minimum word length, a popup will show words or phrases starting with that value. We'll create an auto-complete textbox by following these steps.

1.    Create an .aspx page and add the following CSS to <head> tag.

<style type="text/css">
        /*AutoComplete flyout */
            margin: 0px !important;
            background-color: inherit;
            color: windowtext;
            border: buttonshadow;
            border-width: 1px;
            border-style: solid;
            cursor: 'default';
            overflow: auto;
            height: 200px;
            text-align: left;
            left: 0px;
            list-style-type: none;
        /* AutoComplete highlighted item */
            background-color: #ffff99;
            color: black;
            padding: 1px;
        /* AutoComplete item */
            background-color: window;
            color: windowtext;
            padding: 1px;

2.    Add a ToolkitScriptManager to <form> tag.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">

3.    Add an textbox and button servercontrol to <form> tag. Here, we use javascript “onkeydown” event to caugh the “Enter” press.

<asp:TextBox ID="txtQuery" runat="server" Width="300px" Height="20px" autocomplete="off" onkeydown="if(window.event.keyCode == 13){document.getElementById('btnSearch').click();};"></asp:TextBox><asp:Button ID="btnSearch" OnClick="btnSearch_Click" runat="server" Text="Search" CausesValidation="False">

4.    Add the following button click event in code-behind.

protected void btnSearch_Click(object sender, EventArgs e)
            if (txtQuery.Text != "")
          //when you press “Search” button, it go to search.aspx.
                Response.Redirect("~/search.aspx?query=" + txtQuery.Text);
                //you need to get “query” QueryStirng for further processing in search.aspx page.

5.    Add an AutoCompleteExtender as below.

<asp:AutoCompleteExtender ID="autoComplete1" runat="server" DelimiterCharacters=";,:"      CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem" CompletionListItemCssClass="autocomplete_listItem"        CompletionListCssClass="autocomplete_completionListElement" CompletionSetCount="20" EnableCaching="true" CompletionInterval="500" MinimumPrefixLength="1" ServiceMethod="GetCompletionList"        ServicePath="AutoComplete.asmx" TargetControlID="txtQuery" BehaviorID="AutoCompleteEx"> 

6.    Add an AutoComplete.asmx and put the following code. It use Microsoft Enterprise Library (Microsoft.Practices.EnterpriseLibrary.Data.dll) to get the data access. So, we nee to add .dll to bin folder.

using System.Data;
using Microsoft.Practices.EnterpriseLibrary.Data;
public class AutoComplete : System.Web.Services.WebService
private Database getDBConn()
//To get sql connection.
            Database sqlDB = DatabaseFactory.CreateDatabase("sqlConn");
            return sqlDB;
        public string[] GetCompletionList(string prefixText)
            DataSet ds = null;
            List<string> items = new List<string>(50);
                Database DB = getDBConn();
                ds = DB.ExecuteDataSet("GetProductsWithPrefix", prefixText);

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            catch (Exception ex)
                items = null;
            return items.ToArray();

7.    Add the Sql server connection in web.config look like below. We use "Northwind" database and it depends on your server setting.

    <add name="sqlConn" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;User ID=sa;Password=sa@sa"
      providerName="System.Data.SqlClient" />

8.    Add the following stored procedure into “Northwind” database.

USE [Northwind]
CREATE PROCEDURE [dbo].[GetProductsWithPrefix]
    @keyword nvarchar(100)
 SELECT TOP 50 ProductName  FROM Products WHERE ProductName LIKE @keyword + '%' ORDER BY ProductID DESC

By default, the AutoCompleteExtender will not display suggestions until after you have typed at least 3 characters. I changed  this default behavior by modifying the AutoCompleteExtender MinimumPrefixLength property.

More detail about AutoCompleteExtender :


  1. 5. Add an AutoCompleteExtender as below.

    Where add this code

  2. It is better to put before closing form tag <⁄form> directly. Thank.