Sunday, October 9, 2011

Auto Complete in ASP.NET using Ajax

 Download Files:
AJAXAutoCompleteExtender.zip




Introduction:

AutoComplete is an ASP.NET AJAX extender that can be attached to any TextBox control, and will associate that control with a popup DropDown like list of words that begin with the prefix typed into the textbox.

Create a new website using ASP.NET Ajax-Enabled Web Site:


Now drag and drop three controls on page. ScriptManager, Textbox, AutoCompleteExtender.

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <div>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <cc1:AutoCompleteExtender ID="AutoCompleteExtender1"
            runat="server"
            ServicePath="WebService.asmx"
            ServiceMethod="FindName"
            MinimumPrefixLength="1"
            TargetControlID="TextBox1">
            </cc1:AutoCompleteExtender>
        </div>
    </form>
Now add a new WebService class:


Here is web service code.
Imports System
Imports System.Collections.Generic
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Data.SqlClient
Imports System.Data
Imports System.Data.Common
Imports AtlasTextBoxAutoComplete.DL
Imports System.Collections

<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<System.Web.Script.Services.ScriptService()> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class WebService
    Inherits System.Web.Services.WebService 
    <WebMethod()> _
        <System.Web.Script.Services.ScriptMethod()> _
        Public Function FindName(ByVal prefixText As String, ByVal count As Integer) As String()
        'return all records whose Title starts with the prefix input string
        Dim titleArList As New List(Of String)()
        Dim drProducts As SqlDataReader = sqlProductProvider.GetNameList(prefixText)
        While drProducts.Read()
            Dim strTemp As String = Convert.ToString(drProducts("Name"))
            titleArList.Add(strTemp)
        End While
        Return titleArList.ToArray()
    End Function
End Class

Result will look like this:


I am adding two classes in App_Code folder for database connectivity. You shoudl change your web.config key for database connection string. I am attaching my database in App_Code folder.