AJAX Auto Complete Extender Part 1 of 2 - (Part 1 With Webservice)

Posted by in ASP.NET category on for Intermediate level | Points: 250 | Views : 5894 red flag

In this article we will be using AJAX Auto Complete Extender to have a drop down like feel when we type in the textbox


In real world application development we are given a task to develop an auto complete feature just as Google has when we type something in Google Search text Box, the matching criteria is shown in a drop down look.In order to achieve this we will be using AJAX Auto Complete Extender.


  1. Defining Web Method in WebService for Getting data from Database.
  2. Understanding AJAX Auto Complete extender.

Using the code

  1. Create an Empty Website in VS 2010.Add a Webform
  2. Now drag and drop 1 label and 1 Textbox.
  3. Now Right Click on Web Site -> Add New Item -> Select Web Service -> Name it as AutoComplete.
  4. Once you create the webservice an AutoComplete.cs will be automatically added to App_Code folder.
Explanation of Web Method for Getting data from database.

  1. First we will uncomment the line [System.Web.Script.Services.ScriptService] since we are using AJAX component.
  2. Then we create a Web-method and define a function which has a return type a string array the function will take a string variable as an argument.
  3. Now in the method We will define a list which is type of string.
  4. Then we write our SQL Query to get data from database and dill the data from data apdapter to dataaset.
  5. Now we declare a string array named as countryName and get the Count of the records that are fetched from the Query.
  6. We then run a foreach loop to the data rows in the dataset and then we set the value of the country name to the column of the table i.e. Countries.
  7. Finally we return the countryname variable as our function has a return type of string array.

Screen :- Adding of Web Service

Understanding the AJAX Auto Complete Extender.

  1. TargetControlID :- It will hold the ID of the textbox that will be used for auto-complete
  2. MinimumPrefixLength :- The count of characters required to enter by the user to fetch data from the database matching the Character.
  3. ServicePath :- The path of the webservice where it is located.
  4. ServiceMethod :- The name of the webmethod that we have used to get data from database in the web service.(Note :- Name of the web method should be case sensitive).
Lets Start Implementation
// HTML Mark UP
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AutoCompleteWithoutWebService.aspx.cs"
    Inherits="AutoCompleteWithoutWebService" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <style type="text/css">
            font-family: "Cooper Black";
            font-size: x-large;
    <form id="form1" runat="server">
    <asp:ToolkitScriptManager ID="Toolkitscriptmanager1" runat="server">
                <asp:ServiceReference Path="AutoComplete.asmx" />
    <div class="style1" style="text-align: center">
        AJAX AutoComplete Sample using With Web Service<br />
        <br />
    <p style="text-align: center">
        <asp:Label ID="Label1" runat="server" CssClass="style1" Text="Type Name of Countries"></asp:Label>
        <asp:TextBox ID="xtxtCountries" runat="server" Height="26px" Width="199px"></asp:TextBox>
        <asp:AutoCompleteExtender ID="xtxtCountries_AutoCompleteExtender" runat="server" 
            MinimumPrefixLength="1" Enabled="True" CompletionSetCount="3"  EnableCaching="true" ServicePath="AutoComplete.asmx"
            ServiceMethod="GetCountries" TargetControlID="xtxtCountries">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;

/// <summary>
/// Summary description for AutoComplete
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
public class AutoComplete : System.Web.Services.WebService {

    public AutoComplete () {

        //Uncomment the following line if using designed components 

    public string[] GetCountries(string prefixText)
            List<string> fetchCountries = new List<string>();
            SqlConnection sqlconn = new SqlConnection("Data Source=.;Initial Catalog=DNF;Persist Security Info=True;User ID=sa;Password=sqluser");
            SqlCommand cmdselect = new SqlCommand("select Countries from Countries where Countries like '" + prefixText + "%' ", sqlconn);
            cmdselect.CommandType = CommandType.Text;
            cmdselect.Parameters.AddWithValue("@CountryPrefix", prefixText);
            SqlDataAdapter selectda = new SqlDataAdapter(cmdselect);
            DataSet ds = new DataSet();

            string[] countryName = new string[ds.Tables[0].Rows.Count];
            int i = 0;
            foreach (DataRow dr in ds.Tables[0].Rows)
                countryName.SetValue(dr["Countries"].ToString(), i);
        catch { }
            return countryName;

Note :- In the html mark up, we have added a Tool Script manager, inside the Tool Script manager we will have to add ServiceReference and the path for the webservice so that no issue arises.

Output Screen :-


The following task can also be achieved without Web Service as well that we will see in the next part where we will create a Web Method in the Code behind itself

Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: Raj Trivedi
Member Level:
Member Status: Member,MVP
Member Since: 6/16/2012 2:04:41 AM
Country: India
Regard's Raj.Trivedi "Sharing is Caring" Please mark as answer if your Query is resolved
Raj Trivedi i.e. me started my career as Support Professional and then moved on the Software development eventually reached at these skills Software Development | Enthusiastic Blogger | Content Writer | Technical Writer | Problem Solver | Lecturer on Technology Subjects | Runnerup Award Winner on www.dotnetfunda.com and firm believer in Sharing as a way of Caring Yet this much achieved its still a long way to go and there is biggest dream lying to be one of the best entrepreneurs of India in Technology Department. The Dream has just started and i hope it follows. Highlights are mentioned in details in my profile at http://in.linkedin.com/pub/raj-trivedi/30/61/b30/

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)