Ajax AutoCompleteExtender control example in asp.net C#,VB.Net using web service

Introduction: In previous articles i explained  Ajax AutoCompleteExtender control example in asp.net using C#,VB.Net without using web service and Ajax CascadingDropDown example in asp.net to Fill DropDownList with Countries,states and cities and Accordion example to create Vertical DropDown menu and Create contact us form and Ajax HtmlEditorExtender control to format textbox text and send formatted text in email and TabContainer example to create multiple tabs/panels and  How to allow only numbers, characters in the textbox using FilteredTextBoxExtender control of Ajax in asp.net" and "CalendarExtendar control of Ajax in asp.net
Now in this article i am going to explain How to use Ajax AutoCompleteExtender control in asp.net using  C# and VB.Net using web service. 

AutoCompleteExtender control example of AJAX in asp.net using web service
Description: Have you ever noticed how the related suggestions highlights as you start typing in the Google search box? This is called AutoComplete. So if you want Google type auto complete textbox functionality then we can also implement this functionality in our asp.net web applications using AutoCompleteExtender control of AJAX. AJAX is very powerful tool for improving performance, look and feel. 

The concept is simple. When you start typing in the TextBox, AutoCompleteExtender fetches the matching strings from the database and display while typing e.g. when you type a single character ‘m’ in the TextBox then all the Qualifications starting with ‘m’ will be fetched  and displayed.

There are two ways to implement AutoComplete functionality:

1) Using Web Service
2) Using Static Method

In this example we will learn the first method i.e. auto complete  using Web Service.
I will explain How to show automatic suggestions from database using AutoCompleteExtender control using Static Method in my next article. 

Implementation: Let's create an asp.net sample website application to see it in action.
  •  Create  a DataBase in SQL Server e.g. "MyDataBase"and create a table in that DataBase and Name it "Qualification_ Table" as shown in figure below:
AutoCompleteExtender control example of AJAX in asp.net
 
  • Create ConnectionString in the web.config file as :

<connectionStrings>
    <add name="conStr" connectionString="Data Source=LALIT;Initial Catalog=MyDataBase;Integrated Security=True"/>
  </connectionStrings>

Note: Replace the Data Source and the Initial Catalog as per your application.

In the <Body> tag of  the design page place a ToolScriptmanager from the AjaxControlToolkit toolbox and Place a TextBox control. Also drag AutoCompleteExtender control form Ajax toolkit.  
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
<fieldset style="width:260px;">
            <legend>AutoCompleteExtender control example</legend>    
          Qualification:    <asp:TextBox ID="txtQualifications" runat="server"></asp:TextBox>
            <asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
             TargetControlID="txtQualifications"
             ServicePath="Qualifications.asmx"
             ServiceMethod ="FetchQualifications"
             MinimumPrefixLength="1"
             CompletionSetCount="20"
             CompletionInterval="0"
             EnableCaching="true">
            </asp:AutoCompleteExtender>       
            </fieldset>
  • Notice that on the design page(.aspx) a new directive:
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
is automatically added on dragging the AutoCompleteExtender control form Ajax toolkit in the very second line just below the <@page> directive which is always very first line of the design page(.aspx)
  • The properties of AutoCompleteExpender con troll that are used in this example are as follows:
TargetControlID - The TextBox control where the user types content to be automatically completed e.g. In our case Qualification TextBox.

ServicePath: The path of the Web service from where extender will call the method to fetch the Qualifications.

ServiceMethod - The web service method that we created for fetching The list of Qualifications from the database. 

MinimumPrefixLength - Minimum number of characters that must be entered before getting suggestions e.g. if you type ‘a’ then matching string starting with character ‘a’ will appear.

CompletionInterval - Time in milliseconds when the timer will kick in to get suggestions using the web service. Always keep it as low as you can so that it fetches the suggestion immediately. If you set CompletionInterval  =1000 then it means it  is set to 1 second because 1000 milliseconds =1 second.

EnableCaching – It is a Boolean property to check whether client side caching is enabled or disabled.

CompletionSetCount - Number of suggestions to be retrieved from the web service.

C#.NET Code to implement auto complete on TextBox in asp.net
  • Add a web service in the  project: for this go to Website menu -> Add new item -> select Web Service and name it Qualifications.asmx as shown in fig below:

  • Qualifications.asmx web service will be added in your project and a new folder App_Code will also be created in your project and under this folder there will be Qualifications.cs file as shown in fig below.
AutoCompleteExtender control example of AJAX in asp.net
  • Now in the Qualifications.cs file create a web method and it will look like as :
/// <summary>
/// Summary description for Qualifications
/// </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.
 [System.Web.Script.Services.ScriptService]
public class Qualifications : System.Web.Services.WebService {

    public Qualifications () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public List<string> FetchQualifications(string prefixText)
{
    System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["conStr"].ToString());
    con.Open();
    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("select * from Qualification_Table where Qualification like @QualName+'%'", con);
    cmd.Parameters.AddWithValue("@QualName", prefixText);
    System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(cmd);
    System.Data.DataTable dt = new System.Data.DataTable();
    da.Fill(dt);
    List<string> QualNames = new List<string>();
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        QualNames.Add(dt.Rows[i][1].ToString());
    }
    return QualNames;
    } 
}
.  
VB.NET Code to implement auto complete on TextBox in asp.net
  • Add a web service in the  project: for this go to Website menu -> Add new item -> select Web Service and name it Qualifications.asmx as shown in fig below:
AutoCompleteExtender control example of AJAX in asp.net
Click on the image to enlarge

  • Qualifications.asmx web service will be added in your project and a new folder App_Code will also be created in your project and under this folder there will be Qualifications.vb file as shown in fig below
AutoCompleteExtender control example of AJAX in asp.net
  • Now in the Qualifications.vb file create a web method and it will look like as :
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
 Public Class Qualifications
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function FetchQualifications(prefixText As String) As List(Of String)
        Dim con As New System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("conStr").ToString())
        con.Open()
        Dim cmd As New System.Data.SqlClient.SqlCommand("select * from Qualification_Table where Qualification like @QualName+'%'", con)
        cmd.Parameters.AddWithValue("@QualName", prefixText)
        Dim da As New System.Data.SqlClient.SqlDataAdapter(cmd)
        Dim dt As New System.Data.DataTable()
        da.Fill(dt)
        Dim QualNames As New List(Of String)()
        For i As Integer = 0 To dt.Rows.Count - 1
            QualNames.Add(dt.Rows(i)(1).ToString())
        Next
        Return QualNames
    End Function

  • Now run the website and check by entering single character of the qualification name that is in your Database table. It will show  all the matching Qualifications  starting with entered character.
Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."
Previous
Next Post »

13 comments

Click here for comments
Unknown
admin
August 06, 2013 ×

Lalit, this is 100% - what I was looking for over the past week. If I may ask a quick question, is it possible to merge a couple fields in the lookup such as account name, city, state. When typing in the account name, the end user will know if it is correct based on the visibility of the city and state info.

Thanks

Matt

Reply
avatar
August 06, 2013 ×

thanks matthew for your valuable appreciation.it is always nice to hear that my post helped anyone..and can you please more clarify what is your exact requirement..

Reply
avatar
Anonymous
admin
September 21, 2013 ×

sir i have written the same code but its not working

Reply
avatar
September 21, 2013 ×

this article is completely working..i suggest you to please recheck your code and try once again. If still you face problem then let me know, i will help you to sort out the problem.

Reply
avatar
Anonymous
admin
September 24, 2013 ×

hi. code is not working .. i think problem is we are calling web service but didnt pass the argument value .... can u pliz tell me solution.
i already check the code and webservice

thanks

Reply
avatar
September 24, 2013 ×

Hello..i again rechecked the code and its working on my end..Create a new project and try once more..it will surely work..

Reply
avatar
Anonymous
admin
September 30, 2013 ×

sir its working very nice article

Reply
avatar
September 30, 2013 ×

Thanks for your appreciations..stay connected and keep reading for more useful articles like this..

Reply
avatar
Unknown
admin
November 22, 2013 ×

hello sir can u tell me how to write code for static method...

Reply
avatar
Unknown
admin
January 24, 2014 ×

hello lalit,i get some trouble when i add the webservice you said it would generate make new folder "app_code" and the real fact when i add there is no folder add "app_code" im using vs 2010. thanks for your help

Reply
avatar
January 25, 2014 ×

Hello Christian Yonathan
If not created then you can create your own App_Code folder by following the following steps:
1) Right click on the your project in solution explorer.
2) click on add
3) Click on New Folder
4) Name it App_Code
5)Put your Qualification.cs file in that folder

Reply
avatar
Msi sulthan
admin
March 21, 2014 ×

In this code does not work .what i do?

Reply
avatar
March 23, 2014 ×

Hi mohamed ibrahim..what error you are facing?

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..