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 */
        .autocomplete_completionListElement
        {
            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 */
        .autocomplete_highlightedListItem
        {
            background-color: #ffff99;
            color: black;
            padding: 1px;
        }
        /* AutoComplete item */
        .autocomplete_listItem
        {
            background-color: window;
            color: windowtext;
            padding: 1px;
        }
</style>

2.    Add a ToolkitScriptManager to <form> tag.

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

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">
</asp:Button>

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.
            }
            else
            {
                Response.Redirect("search.aspx");
            }
        }

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"> 
</asp:AutoCompleteExtender>

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;
[System.Web.Script.Services.ScriptService]
public class AutoComplete : System.Web.Services.WebService
{
private Database getDBConn()
        {
//To get sql connection.
            Database sqlDB = DatabaseFactory.CreateDatabase("sqlConn");
            return sqlDB;
        }
        [WebMethod]
        public string[] GetCompletionList(string prefixText)
        {
            DataSet ds = null;
            List<string> items = new List<string>(50);
            try
            {
                Database DB = getDBConn();
                ds = DB.ExecuteDataSet("GetProductsWithPrefix", prefixText);

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    items.Add(ds.Tables[0].Rows[i][0].ToString());
                }
            }
            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.

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

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

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

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 :
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/AutoComplete/AutoComplete.aspx

4 comments:

  1. 5. Add an AutoCompleteExtender as below.



    Where add this code

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

    ReplyDelete
  3. And before that, there was only few auto shipping companies, so car shipping rates were considerably higher. Today, however due to increase mobility as well as the fact that we are a more mobile society, the numbers of auto transport companies are increasing. car transport

    ReplyDelete