ASPSnippets

Alerts
Get notified when a new article is published.

Name
 
Email

Your email will always be private and will not be shared.

Follow us on twitter.
 
Using jQuery AutoComplete Plugin in ASP.Net
Author Name: Mudassar Khan Published Date: February 01, 2010
Filed Under :
ASP.Net
 |
AJAX
 |
JQuery
Views: 831
In this article I’ll be explaining how to use jQuery AutoComplete Plugin in ASP.Net. Using jQuery we can easily create AutoComplete Textbox without writing much code.
 
Database
For database I am using the Microsoft’s NorthWind Database. You can download the same using the link below
Download Northwind Database


Connection String
Below is the connection string to the database which I have placed in the web.config.
<connectionStrings>
      <addname="constr"connectionString="Data Source = .\SQLExpress;       
       Initial Catalog = Northwind; Integrated Security = true"/>
</connectionStrings>


Download jQuery
You can download the latest version of jQuery and the AutoComplete Plugin using the links below.
Download jQuery

Download jQuery AutoComplete Plugin
 
AutoComplete Handler
We will need to build a handler that will process all the requests of AutoComplete and return the results back to the ASP.Net Web page
C#
<%@ WebHandler Language="C#" Class="Search_CS" %>
 
using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
 
public class Search_CS : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
        string prefixText = context.Request.QueryString["q"];
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager
                    .ConnectionStrings["constr"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "select ContactName from Customers where " +
                "ContactName like @SearchText + '%'";
                cmd.Parameters.AddWithValue("@SearchText", prefixText);
                cmd.Connection = conn;
                StringBuilder sb = new StringBuilder();
                conn.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        sb.Append(sdr["ContactName"])
                            .Append(Environment.NewLine);
                    }
                }
                conn.Close();
                context.Response.Write(sb.ToString());
            }
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}
 
VB.Net
<%@ WebHandler Language="VB" Class="Search_VB" %>
 
Imports System
Imports System.Web
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Text
 
Public Class Search_VB : Implements IHttpHandler
   
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim prefixText As String = context.Request.QueryString("q")
        Dim conn As SqlConnection = New SqlConnection
        conn.ConnectionString = ConfigurationManager _
                .ConnectionStrings("constr").ConnectionString
        Dim cmd As SqlCommand = New SqlCommand
        cmd.CommandText = ("select ContactName from Customers where " & _
                           "ContactName like @SearchText + '%'")
        cmd.Parameters.AddWithValue("@SearchText", prefixText)
        cmd.Connection = conn
        Dim sb As StringBuilder = New StringBuilder
        conn.Open()
        Dim sdr As SqlDataReader = cmd.ExecuteReader
        While sdr.Read
            sb.Append(sdr("ContactName")) _
                .Append(Environment.NewLine)
        End While
        conn.Close()
        context.Response.Write(sb.ToString)
    End Sub
 
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property
End Class
 
The above handler accepts the request from jQuery in a Querystring parameter q. Based on the value of this parameter the handler searches the customer table and returns the customers whose names match the substring queried by the user.
 
Client Side Implementation
Below I have described the Client Side implementations of jQuery AutoComplete Plugin. Both the versions C# and VB.Net are exactly same except the URL of the handler.
C# Version
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
<link href="css/jquery.autocomplete.css" rel="stylesheet" type="text/css" />
<script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="scripts/jquery.autocomplete.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("#<%=txtSearch.ClientID%>").autocomplete('Search_CS.ashx');
    });      
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
    </div>
    </form>
</body>
</html>
 
VB.Net Version
<head id="Head1" runat="server">
<title></title>
<link href="css/jquery.autocomplete.css" rel="stylesheet" type="text/css" />
<script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="scripts/jquery.autocomplete.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $("#<%=txtSearch.ClientID%>").autocomplete('Search_VB.ashx');
    });      
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
    </div>
    </form>
</body>
 
Above you have noticed how easy it is to configure the jQuery AutoComplete Plugin. You simply need to inherit the required JS Files, place a textbox and write the below small snippet
<script type="text/javascript">
    $(document).ready(function() {
        $("#<TextBoxControlId>").autocomplete('<Url of handler>');
    });      
</script>
 
AJAX Autocomplete Extender using jQuery in ASP.Net
 
 
With this we come to end of this article. You can download the source code in VB.Net and C# using the link below.
JQueryAutoCompleteinASP.Net.zip
 

If you like this article, help us grow by bookmarking this page on any social bookmarking site.
Bookmark and Share Page copy protected against web site content infringement by Copyscape

Related Articles

Comments

krunal said:
I required autocomplete functionality in a gridview so i made a usercontrol and put into the gridview Item Template but as runtime it creates the new id (same as number of rows in gridview) i am not able to get autocomplete functionality in gridview.
February 08, 2010  

Mudassar Khan said:
Reply To: krunal
You can place the script tag inside the itemtemplate below the textbox
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<script type="text/javascript">
$(document).ready(function() {
$("#<%=txtSearch.ClientID%>").autocomplete('Search_VB.ashx');
});
</script>

I am sure it will work
February 08, 2010  

Mudassar Khan said:
Reply To: krunal
In that case you will have to Add a literal control to the item template and induce this javascript dynamically on rowdatabound event
February 08, 2010  

okkk said:
hi br br its not work for me br br i donwnload ur zip only and run it but no suggestions i didnt download jquery and autocomplete from their websites i copy and paste them from ur zep file can u help me and i should use internet to be able to use them
February 13, 2010  

Mudassar Khan said:
Reply To: okkk
There is no need for internet just download the northwind database
February 15, 2010  

Add Comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
There is no need to add BR tags. Simply press enter for new line

Name*  
Email*
Comment*  
Security code
Security code