Click here to Skip to main content
Licence CPOL
First Posted 3 Sep 2010
Views 21,397
Bookmarked 43 times

Ajax AutoComplete in ASP.NET

Ajax AutoComplete in ASP.NET
A Technical Blog article. View original blog here.[^]

Without using AjaxControlToolKit, we can implement AutoComplete Extender using pure Ajax Call. This article explains how to do make AutoComplete Extender.

OnKeyUp event helps you to fetch data from database with Ajax call. Here one Handler.ashx handles the AJAX request form Client. I add a Class file to handle database operations to better coding practice. Below I explain the database helper Class. Class has one method:

GetTable(string sqlQuery) 

This returns DataTable after fetching data from database. And also includes Provide Class, this Class helps to get SqlConnection string.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
/// <summary>
/// Summary description for DBHelper
/// </summary>
public class DBHelper
{
    SqlConnection connection;
    SqlDataAdapter adapter;
    SqlCommand command;
    DataTable dataTable;
    public DBHelper()
    {
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sqlQuery">passing SQL Query here
    /// <returns>DataTable object is returned</returns>
    public DataTable GetTable(string sqlQuery)
    {
        //creating new instance of Datatable
        dataTable = new DataTable();
        connection = Provider.GetConnection();
        command = new SqlCommand(sqlQuery, connection);
        //Open SQL Connection
        connection.Open();
            try
            {
                adapter = new SqlDataAdapter(command);
                adapter.Fill(dataTable);
            }
            catch
            { }
            finally
            {
                //Closing Sql Connection 
                connection.Close();
            }
        return dataTable;
    }
}
public class Provider
{
    public static SqlConnection GetConnection()
    {
        //creating SqlConnection
        return new SqlConnection(ConfigurationManager.AppSettings["sqlConn"]);
    }
} 

Now we can look into Handler file. When request comes from Ajax Call from Client, it passes the data into our Database helper Class, handler file holds the data in DataTable. Result data are formatted in a table and written in the context. We can add JavaScript function for selecting the data, here api_helper.AddtoTaxtBox(selectedItem) manages client section of data.

Check Handler File

<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Data;
public class Handler : IHttpHandler {
    public void ProcessRequest (HttpContext context) {

        HttpRequest request = HttpContext.Current.Request;
        //checking string null or empty
        if (!string.IsNullOrEmpty(request.QueryString["name"]))
        {
            string name=request.QueryString["name"];
            //creating instance of new database helper
            DBHelper objDBHelper = new DBHelper();
            //creating Sql Query
            string sqlQuery = string.Format
		("SELECT Name FROM User WHERE Name LIKE '{0}%'", name);
            //filling data from database
            DataTable dataTable = objDBHelper.GetTable(sqlQuery);

             string table = string.Empty;
            //table for hold data
            table = "<table width='100%'>";
            string td = string.Empty;
            //checking datatable
                if (dataTable.Rows.Count > 0)
                {
                    for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        //adding table rows
                        td += string.Format("<tr><td class='select' 
			onclick='api_helper.AddtoTaxtBox(this.innerHTML)'>
			{0}</td></tr>", dataTable.Rows[i][0].ToString());
                    }
                }
                table += td + "</table>";
                context.Response.Write(table);
        }
    }
    public bool IsReusable {
        get {
            return false;
        }
    }
}

Now we can check how Ajax works. On Textbox onKeyUp event, call the Ajax code. It sends the entered value into server using Ajax and the result is displayed in div control under the search textbox.

<%@ Page Language="C#" AutoEventWireup="true"  
	CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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">
<title></title>
</head>
<body>
     <form id="form1" runat="server">
       <div>

         <asp:TextBox ID="txtName" runat="server" 
		onkeyup="api_helper.callAjax();"></asp:TextBox>
           <div id="myDiv"></div>
           
      </div>
             <script language="javascript" type="text/javascript">

               if (typeof (api_helper) == 'undefined') { api_helper = {} }

               api_helper.doAjax = function(HandlerUrl, displayDiv) {
                var Req; try { Req = new XMLHttpRequest(); } 
		catch (e) { try { Req = new ActiveXObject("Msxml2.XMLHTTP"); }
		catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } 
		catch (e) { return false; } } } Req.onreadystatechange = function() {
		if (Req.readyState == 4) { var d = document.getElementById(displayDiv); 
		d.innerHTML = Req.responseText; } }
                Req.open("GET", HandlerUrl, true); Req.send(null);
              }

               api_helper.callAjax = function() {
                var text = document.getElementById("txtName").value;
                if (text != "") {
                    var requestUrl = "Handler.ashx?name=" + text;
                    var displayDiv="myDiv";
                    api_helper.doAjax(requestUrl, displayDiv);
                }
              }

              api_helper.AddtoTaxtBox = function(txt) {
                document.getElementById("txtName").value = txt;
                document.getElementById("myDiv").innerHTML = "";
              }
            </script>         
     </form>
  </body>
</html>  

Sample  ;

 

Thanks for reading this article. Please feel free to comment.

Tags Ajax AutoComplete, Ajax Example.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

raju melveetilpurayil



United Kingdom United Kingdom

Member

Microsoft Certified Professional Developer.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 4 PinmemberLeonardo Paneque12:07 24 Apr '12  
GeneralMy vote of 5 Pinmemberjpmontoya1829:03 11 Jan '12  
GeneralMy vote of 2 Pinmemberstian.net23:32 29 Dec '11  
GeneralMy vote of 5 PinmemberSuraj S Koneri22:36 28 Nov '11  
GeneralRe: My vote of 5 Pinmemberraju melveetilpurayil0:21 29 Nov '11  
GeneralMy vote is 5 PinmemberAli Al Omairi9:59 28 Dec '10  
GeneralRe: My vote is 5 Pinmember[raju.m][makhaai]13:17 23 Jan '11  
GeneralMy vote of 5 PinmemberAli Al Omairi9:56 28 Dec '10  
GeneralRe: My vote of 5 Pinmember[raju.m][makhaai]16:15 21 Mar '11  
GeneralMy vote of 5 PinmemberShahriar Iqbal Chowdhury23:44 16 Nov '10  
GeneralMy vote of 5 PinmentorBrij6:33 15 Oct '10  
GeneralMy vote of 5 PinmemberRehan Hussain21:14 10 Oct '10  
GeneralRe: My vote of 5 Pinmember[raju.m][makhaai]0:26 15 Oct '10  
GeneralMy vote of 5 Pinmemberswapna.kurian7:26 9 Oct '10  
GeneralRe: My vote of 5 Pinmember[raju.m][makhaai]20:21 9 Oct '10  
GeneralMy vote of 5 PinmemberShohelShipon20:34 3 Oct '10  
GeneralNICE Pinmemberkashyap201019:54 6 Sep '10  
GeneralRe: NICE Pinmember[raju.m][makhaai]12:56 7 Sep '10  
GeneralRe: NICE Pinmembershakil03040035:37 19 Oct '10  
GeneralRe: NICE Pinmember[raju.m][makhaai]5:40 19 Oct '10  
GeneralMy vote of 5 Pinmembersenpaulose4:43 4 Sep '10  
GeneralRe: My vote of 5 Pinmemberraju makhaai0:10 6 Sep '10  
GeneralRe: My vote of 5 PinmemberEbenRoux18:52 6 Sep '10  
GeneralRe: My vote of 5 Pinmember[raju.m][makhaai]13:02 7 Sep '10  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 19 Oct 2010
Article Copyright 2010 by raju melveetilpurayil
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid