Home > AJAX, ASP.Net > AutoComplete from Database with HttpRequest

AutoComplete from Database with HttpRequest


Hi

try this Example :-

in this example i will use Northwind Database and Products table

step 1 :- create web site and add two pages Default.aspx and Default2.aspx

step 2 : in page Default.aspx add TextBox control

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.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>Untitled Page</title>
 
 <script language="javascript" type="text/javascript">
var xmlHttp;
function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}
//--------------------------
function callAjaxShowDiv(value)
 {
    xmlHttp = GetXmlHttpObject();
    if (xmlHttp==null)
    {
        alert ("Browser does not support HTTP Request");
         return;
    }
    if (value != '')
    {      
            document.getElementById("dd").innerText =  "Loading >>>>"
            //you can provide your page URL which will fetch you the values from your database
            var url = "Default2.aspx";
            url = url + "?ProductName=" +value;

            //state change event-this will occur ass soon as response comes from the url
            xmlHttp.onreadystatechange = stateChanged;
            xmlHttp.open("GET",url,true);
            xmlHttp.send(null);
    }
    else
    {
      document.getElementById("dataDiv").style.visibility='hidden';
    }
 }

//event
function stateChanged()
{
//for a succesful event ready state  value of the xmlhttp object must contain these values
  if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
  { //Display contents
 
    var xmlResponse = xmlHttp.responseText;
    if (xmlResponse!='')
        {
            document.getElementById("dataDiv").innerHTML ="";
             document.getElementById("dataDiv").style.visibility='visible';
            document.getElementById("dataDiv").innerHTML = xmlResponse;
            document.getElementById("dd").innerText =  "";
        }
        else
        {
            //document.getElementById("dataDiv").innerHTML ="";
            document.getElementById("dd").innerText =  "";
            document.getElementById("dataDiv").style.visibility='hidden';
        }
     }
} 
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div >
   
    <div id="dd"></div>
      
    </div>
        <table style="width: 443px"   >
            <tr>
                <td>
     Please Enter Producr Name :-</td>
                <td >
    <input name="Text1" id="Text1" type="text" onkeyup="callAjaxShowDiv(this.value) " style="width: 192px" /></td>
            </tr>
            <tr>
                <td>
                </td>
                <td>
    <div id="dataDiv" runat="server" style="overflow:scroll; overflow-x:hidden; overflow-y:scroll; width:200px;

height:100px; visibility:hidden">

    </div>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

step3 : in Default2.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Text;
using System.Xml;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
            string ProductName = Request.QueryString["ProductName"].ToString();
            Response.Clear();
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.Now);
            string connectionstring = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = connectionstring;
            conn.Open();
            SqlCommand comm = new SqlCommand("select ProductName from Products where ProductName like '" + ProductName + "%'", conn);
            SqlDataReader dr = comm.ExecuteReader();
            if (dr.HasRows)
            {
                Response.Write("<table border=1 cellspacing=0 cellpadding=0 bgcolor=gray width=200px >");
                while (dr.Read())
                {
                    Response.Write("<tr><td onclick=\"" + "document.getElementById('Text1').value=this.innerText;document.getElementById('dataDiv').style.visibility='hidden'\" onmouseover=\"style.background='blue';style.cursor='hand'\" onmouseout=\"style.background='dray'\" >");
                    // Response.Write("<tr><td onclick=\"" + "document.getElementById(\"Text1\").value=this.innerText\">");
                    Response.Write(dr.GetString(0));
                    Response.Write("</td></tr>");

                }
                Response.Write("</table>");
            }
            dr.Dispose();
            conn.Close();
            Response.End();
    }
}

Hope this helps

you can download code Here

Good Luck

Advertisements
Categories: AJAX, ASP.Net Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: