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

AutoComplete from Database with HttpRequest Another way


Hi

in previous post i posted how to create AutoComplete from Database with HttpRequest or without using AJAX Toolkit

you can check this link from Here

i this example i will use Northwind Database and Categories , Orders tables

Step1:- create a website and add two web pages (Default , LookUp pages )and js file (JSFile.js)

Step2:- in Default.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>">

<html xmlns="<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>" >
<head runat="server">
    <title>How to Create You Own Auto Suggest Page</title>
    <script language="javascript" type="text/javascript" src="JSFile.js"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    </div>
        <table border="0" cellpadding="0" cellspacing="0" width="600">
            <tr>
                <td align="center" height="50">
                    <asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Italic="False" Font-Names="Raavi"
                        Font-Size="18pt" ForeColor="Blue" Text="How to create your own Auto Suggest feature without the AJAX Framework?"></asp:Label></td>
            </tr>
            <tr>
                <td align="left" height="300" valign="top">
                    <br />
                    <asp:Label ID="LabelCategory" runat="server" Font-Names="Tahoma" Font-Size="10pt"
                        Text="Choose a Category:" Width="200px"></asp:Label>
                    <asp:TextBox ID="TextBoxCategory" runat="server" Font-Names="Tahoma" Font-Size="10pt" Width="250px"></asp:TextBox>
                    <DIV id="DivAutoCompleteCategory1" runat="server" style="BACKGROUND-COLOR: #ccccff" align="left"></DIV>
                    <br />
                    <asp:Label ID="LabelShipmentName" runat="server" Font-Names="Tahoma" Font-Size="10pt"
                        Text="Choose a Order Shipment Name:" Width="200px"></asp:Label>
                    <asp:TextBox ID="TBShipmentName" runat="server" Font-Names="Tahoma" Font-Size="10pt" Width="250px"></asp:TextBox>
                    <DIV id="DivAutoCompleteShipmentInfo" runat="server" style="BACKGROUND-COLOR: #ccccff" align="left"></DIV>
                    </td>
            </tr>
        </table>
    </form>
</body>
</html>

and in code behind :-

using System;
using System.Data;
using System.Configuration;
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;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            this.TextBoxCategory.Attributes["autocomplete"] = "off";
            this.TBShipmentName.Attributes["autocomplete"] = "off";

            //Add attribute to call js to fetch data
            //using the JavaScript function: SendQuery
            //Paramaters include
            // 1.  The current typed text value
            // 2.  Div ID where to show similar results
            // 3.  URL to call by AJAX passing Mode to so we know what to query
            // 4.  Textbox where to return the data
            this.TextBoxCategory.Attributes["onkeyup"] = "SendQuery(this.value, '" +
                this.DivAutoCompleteCategory1.ClientID +
                "', '/HowToCreateAnAutoSuggest/LookUp.aspx?Mode=Category&TB=" +
                this.TextBoxCategory.ClientID + "')";

            this.TBShipmentName.Attributes["onkeyup"] = "SendQuery(this.value, '" +
                this.DivAutoCompleteShipmentInfo.ClientID +
                "', '/HowToCreateAnAutoSuggest/LookUp.aspx?Mode=Shipment&TB=" +
                this.TBShipmentName.ClientID + "')";
           
        }
    }
}

Step3:- in LookUp.aspx page add this code :

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;

public partial class LookUp : System.Web.UI.Page
{
    protected void Page_Load(object sender, System.EventArgs e)
    {
        string keyword = Request["k"];
        string Mode = Request["Mode"];
        string ReturnTextbox = Request["TB"];
        string MyDiv = Request["MyDiv"];

        if (keyword != null && Mode != null && keyword.Trim().Length > 0)
        {
            //build div items based on what is in database, and what user typed.
            string sql = "";
            if (Mode == "Category")
            {
                sql = "SELECT distinct TOP 5 CategoryName from Categories Where CategoryName like '" +
                    keyword.Replace("'", "''") + "%'";
            }
            else if (Mode == "Shipment")
            {
                sql = "SELECT distinct TOP 5 ShipName from Orders Where ShipName like '" +
                    keyword.Replace("'", "''") + "%'";
            }
            else
            {
                return;
            }

            DataSet ds = new DataSet();
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
            conn.ConnectionString = "Data Source=.;Initial Catalog=Northwind;Integrated Security=True";
            System.Data.SqlClient.SqlDataAdapter adapter =
                new System.Data.SqlClient.SqlDataAdapter(sql, conn);
           
            adapter.Fill(ds);

            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = new DataTable();
                dt = ds.Tables[0];
                foreach (DataRow row in dt.Rows)
                {
                    string mydata = row[0].ToString();

                    if (ReturnTextbox != null && ReturnTextbox.Trim().Length > 0)
                    {
                        if (MyDiv == null || MyDiv.Trim().Length == 0)
                        {
                            Response.Write("<div onmouseover=\"this.style.cursor='pointer';\"" +
                                "onmouseout=\"this.style.cursor='pointer';\"" +
                                "onclick=\"SetTextbox('" +
                                ReturnTextbox.Trim() + "','" +
                                mydata + "', '');\">" +
                                "<font size='2' face='Tahoma'><B>" +
                                mydata +
                                "</B></font>" +
                                "</div>");
                        }
                        else
                        {
                            Response.Write("<div onmouseover=\"this.style.cursor='pointer';\"" +
                                "onmouseout=\"this.style.cursor='pointer';\"" +
                                "onclick=\"SetTextbox('" +
                                ReturnTextbox.Trim() + "','" +
                                mydata + "', '" +
                                MyDiv + "');\">" +
                                "<font size='2' face='Tahoma'><B>" + mydata + "</B></font>" +
                                "</div>");

                        }
                    }
                    else
                    {
                        Response.Write("<div><font size='2' face='Tahoma'><B>" +
                            mydata + "</B></font></div>");
                    }
                }
            }
        }
    }
}

Step4:- and in Js file (Javascript) add this function

var req;
var CurrentDIV;

//Set up to use javascript to call pages
//You do not need to change anything here
function Initialize()
{
 try
 {
  req = new ActiveXObject("Msxml2.XMLHTTP");
 }
 catch(e)
 {
  try
  {
   req = new ActiveXObject("Microsoft.XMLHTTP");
  }
  catch(oc)
  {
   req = null;
  }
 }

 if( !req && typeof XMLHttpRequest != "undefined" )
 {
  req = new XMLHttpRequest();
 }
}

//sends the query to desired page, and returns to div autocomplete
//based on what the user typed
//key paramater has what the user typed.
//div paramater states, which div to stick the data back to.
function SendQuery(key, MyDiv, url)
{
 if ( key == null || key.length == 0 )
 {
  document.getElementById(MyDiv).innerHTML = "";
  HideDiv(MyDiv);
  return;
 }
 CurrentDIV = MyDiv;
 Initialize();
 var url= url + "&k=" + key + "&MyDiv=" + MyDiv;

 if( req != null)
 {
  req.onreadystatechange = Process;
  req.open("GET", url, true);
  req.send(null);
 }
}

//checks is status was good
function Process()
{
 if (req.readyState == 4)
 {
  // only if "OK"
  if (req.status == 200)
  {
   if(req.responseText=="")
    HideDiv(CurrentDIV);
   else
   {
    //alert(req.responseText);
    ShowDiv(CurrentDIV);
    document.getElementById(CurrentDIV).innerHTML =req.responseText;
   }
  }
  else
  {
   document.getElementById(CurrentDIV).innerHTML=
    "There was a problem retrieving data:<br>"+req.statusText;
  }
 }
}

function ShowDiv(divid)
{
 if (document.layers) document.layers[divid].display="block";
 else document.getElementById(divid).style.display="block";
}

function HideDiv(divid)
{
 if (document.layers) document.layers[divid].display = "none";
 else document.getElementById(divid).style.display="none";
}

function SetTextbox( TextboxID, data, MyDiv )
{
    document.getElementById(TextboxID).value = data;
    if ( MyDiv.length > 0 )
    {
        HideDiv( MyDiv );
    }
}

Hope this helps

Good Luck

Advertisements
Categories: AJAX, ASP.Net Tags:
  1. Peter
    April 14, 2009 at 9:13 am

    Hi Yasserzaid,

    I’ve tried to implement this code, but when I submit the form I retrieve the error message:

    The state information is invalid for this page and might be corrupted.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.Web.HttpException: The state information is invalid for this page and might be corrupted.

    Hopefully you have also retrieved this error message so we can solve this problem.

    Best regards,

    Peter

  2. Peter
    April 14, 2009 at 10:28 am

    Sorry, I solved my problem…

    I had added a form inside the lookup.aspx what created a stateview. This stateview was also submitted when I fired a submit from the source page. And the .NET framework 2.0 doesn’t like two viewstates in one __viewstate value… 😉

  3. yasserzaid
    April 14, 2009 at 3:51 pm

    Thank you Peter

    Hope my post helps you

    Best Regards,
    Yasser Zaid

  1. No trackbacks yet.

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: