Monday, 17 March 2014

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

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 ScriptManager from the AJAX Extensions category of visual studio tool toolbox and Place a TextBox control. Also drag AutoCompleteExtender control form Ajax toolkit.  
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> 
<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.

No comments:

Post a Comment