Saturday, December 25, 2010

AJAX - AutoComplete Extender

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.

Let See how to apply AutoCompleteExtender to the textbox control in this example i will bind the list of country name to AutoComplete Extender for getting suggestion country name.

Step 1
Create a Country Table in Database,it is look like this

Step 2
Insert Data in country table,it is look like this

Step 3
Add a new Website in the solution.

Step 4
Add a ToolkitScriptManager control from Ajax toolkit inside the Div Tag,it is look like this


         <asp:ToolkitScriptManager ID="ToolKitScriptManager1" runat="server">

This control allows you to replace the default <asp:scriptmanager> control behavior, and supports the ability to dynamically merge multiple client-side Javascript scripts into a single file that is downloaded to the client at runtime. 

Step 5
Add a textbox control from toolbox and AutoComplete Extender from AjaxToolKit,it is look like this

<asp:TextBox ID="txtCountry" runat="server" ></asp:TextBox>
                <asp:AutoCompleteExtender ID="ACECountry" runat="server" 
                    TargetControlID="txtCountry" ServiceMethod="GetCompletionList" UseContextKey="True" 
                    MinimumPrefixLength="1" CompletionInterval="1" CompletionSetCount="20"  EnableCaching="true">

There are the following basic properties of AutoComplete Extender:

1. TargetControlID
     The TextBox control where the user types content to be automatically completed.

2. ServiceMethod
     The name of the service method.

3. UseContextKey
     Whether or not the ContextKey property should be used. This will be automatically enabled if the ContextKey property is ever set (on either the client or the server). If the context key is used, it should have the same signature with an additional parameter named contextKey of type string (as described above). 

4. MinimumPrefixLength
     Minimum number of characters that must be entered before getting suggestions from the service method.

5. CompletionInterval
    Time in milliseconds when the timer will kick in to get suggestions from the service method.

6. CompletionSetCount
    Number of suggestions to be retrieved from the service method.

7. EnableCaching
    Whether client side caching is enabled.

Step 6
Add a Service method in code behind.Expanding the textbox control smart tag,select the add AutoComplete page method option from the provided menu.This action create a service method in code behind for your page,it is look like this

Click on image for better view.

Step 7
Add a ConnectionString in web.config file,it is look like this

        <add name="ConStr" connectionString="Data Source=SHREE\SHREE;Initial Catalog=ABC;Integrated Security=True" providerName="System.Data.SqlClient"/>

Step 8
Get a country list from database,it is look like this

[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] GetCompletionList(string prefixText, int count, string contextKey)
        List<String> ListCountryName = new List<String>(); // List Object

            // Open the connection
            SqlConnection SqlCon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);

            // Create a Command
            SqlCommand SqlComm = new SqlCommand();
            SqlComm.Connection = SqlCon;

            // Add a CountryName SQl Parameter
            SqlComm.Parameters.Add("@CountryName", SqlDbType.VarChar).Value = prefixText; // retrievable throught prefixText parameter

            // Query for get country name from database 
            SqlComm.CommandType = CommandType.Text;
            SqlComm.CommandText = "SELECT Country.CountryName FROM Country WHERE CountryName LIKE ''+@CountryName+'%' ";

            // Read the data and add in List object.
            SqlDataReader SqlDr = SqlComm.ExecuteReader(); 

            if (SqlDr != null)
                while (SqlDr.Read())
        catch (Exception ex)
            throw new Exception(ex.Message);  

        return ListCountryName.ToArray<String>();

Run the project.

Click on image for better view.

Download Source Code


  1. Just wanted to say thanks; this was the only site that clearly showed how to get autocomplete working with an MSSQL connection that worked for me.

    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
      or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

  2. Thanks a lot Jeff..
    and Most Welcome buddy.

  3. Thankx a lot Sir For Your WonderFull Guidance,this the only code which helped me out .....THANKX.... ONCE AGAIN :)