Click here to Skip to main content
15,881,172 members
Articles / Web Development / ASP.NET

AutoComplete Textbox

Rate me:
Please Sign up or sign in to vote.
3.00/5 (9 votes)
22 Aug 2011CPOL 38.5K   836   13   11
AutoComplete TextBox with simple JavaScript using XMLHTTP Request

AutoCompleteTextbox/textbox.JPG

Introduction

This is a simple Autocomplete Text box post which may help you. In this code, we are using XMLHTTP request object in JavaScript method to get the server data from ASP.NET page.

Using the Code

To achieve this first create two aspx pages one (Default.aspx) is for Autocomplete Text box, another (GetData.aspx) is to get the data from server. No need to write any server side code on Default.aspx.cs page. Just write some JavaScript methods for XMLHTTP request object and key press mouse over events and style for look and feel. See the below code:

HTML
//
   <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Autocomplete Page</title>
    <style type="text/css">
    .row{
	font-family:Verdana, Geneva, sans-serif;
	font-size:11px;
	color:#333;
	background-color:#FFF;
	text-align:left;
}
.highlight{
	font-family:Verdana, Geneva, sans-serif;
	font-size:11px;
	color:#333;
	background-color:#06C;
	text-align:left;
	color:#FFF;
}
    </style>
JavaScript
    <script type="text/javascript">

    function showHint(str)
{
var xmlhttp;
if (str.length==0)
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }

xmlhttp.open("GET","GetData.aspx?username="+str,true);
xmlhttp.send();
}

// key press events

current_row = 1;
var firsttime;
	nn=(document.layers)?true:false;
	ie=(document.all)?true:false;
	function keyDown(e) {

		var evt=(e)?e:(window.event)?window.event:null;
		if(evt){
			var key=(evt.charCode)?evt.charCode: 
			((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
			if (key == 38) {

			    id1 = document.getElementById('xx' + current_row);
			    if (id1) {
			        id2 = document.getElementById('xx' + 
				parseInt(current_row - 1));
			        if (id2) {
			            current_row = current_row - 1;
			            id1.className = 'row';
			            id2.className = 'highlight';
			            document.getElementById('txtname').blur();

			        }
			    }
			}
			else if (key == 40) {
			    id1 = document.getElementById('xx' + current_row);

			    if (id1) {

			            if (current_row == 1 && firsttime == undefined) {
			                id1.className = 'highlight';
			                document.getElementById('txtname').blur();
			                current_row = current_row - 1;
			                firsttime = 1;
			            }
			            else {
			                id2 = document.getElementById('xx' + 
						parseInt(current_row + 1));
			                if (id2) {
			                document.getElementById('xx1').className='row';
			                id1.className = 'row';
			                id2.className = 'highlight';
			                document.getElementById('txtname').blur();
			            }

			        }
			        current_row = current_row + 1;
			    }
			}

			else if (key == 13 || key == 9) {
			    id1 = document.getElementById('xx' + current_row);
			    if (id1) {

			        test(id1.innerHTML);

			    }
			}
			else if (key == 8) {
			current_row = 1;
			firsttime = undefined;
			}
		}
	}
document.onkeydown=keyDown;
if(nn) document.captureEvents(Event.KEYDOWN);
//place the selected value into text box and hide the result set table
function test(rname) {

    document.getElementById('txtname').value = rname;
    var tbl = document.getElementById('tblAuto');
    tbl.style.display = 'none';
}
    </script>
HTML
</head>
<body>
    <form id="form1" runat="server">
        <table>
            <tr>
                <td >
                    <asp:TextBox ID="txtname"  runat="server"
                    onkeyup="showHint(this.value);" TabIndex="1" ></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <span id="txtHint"></span>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

...

And GetData.aspx page should have only the below tag, delete all other content.

ASP.NET
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="GetData.aspx.cs" Inherits="GetData" %>

The below code needs to be written in the GetData.aspx.cs page:

C#
using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;

public partial class GetData : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection
    ("Data Source=.;Initial Catalog=pubs;User ID=sa;password=sa;");
    protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        String strUserLike = Request.QueryString["username"];
        DataSet DS = new DataSet();

        int m;
        SqlDataAdapter ad = new SqlDataAdapter("select lname from employee
        WHERE  lname LIKE '" + strUserLike + "%' AND lname is not null ", con);
        ad.Fill(DS);
        m = DS.Tables[0].Rows.Count;
        sb.Append("<table id='tblAuto' bgcolor='#CCCCCC'>");
        for (int i = 1; i <= m; i++)
        {
            sb.Append("<tr  bgcolor=\"#FFFFFF\" ><td id=\"xx" + i +
            "\"  tabindex=\"2\" class=\"row\" onclick=\"test('" +
            DS.Tables[0].Rows[i-1][0] + "')\"  onmouseover=\"this.className=
            'highlight'\"  onmouseout=\"this.className='row'\">");
            sb.Append(DS.Tables[0].Rows[i-1][0]);
            sb.Append("</td></tr>");
        }
        sb.Append("</table>");

        Response.Write(sb.ToString());

Thanks! If you have any questions or any issues about the code, please drop in a comment below.

License

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


Written By
Software Developer (Senior) Agility E Services
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionThanks Pin
tranquocdung435-Jan-12 17:20
tranquocdung435-Jan-12 17:20 
it's useful for me. Thanks
QuestionCode is not working for chrome and firefox browsers Pin
Member 310337316-Nov-11 4:54
Member 310337316-Nov-11 4:54 
GeneralMy vote of 2 Pin
Praveen Meghwal22-Aug-11 21:59
Praveen Meghwal22-Aug-11 21:59 
GeneralMy vote of 5 Pin
mhamad zarif22-Aug-11 21:29
mhamad zarif22-Aug-11 21:29 
GeneralMy vote of 3 Pin
mbcrump13-Aug-11 12:10
mentormbcrump13-Aug-11 12:10 
GeneralRe: My vote of 3 Pin
Sreedhar Taduri14-Aug-11 18:57
Sreedhar Taduri14-Aug-11 18:57 
GeneralMy vote of 2 Pin
Warrick Procter13-Aug-11 2:43
Warrick Procter13-Aug-11 2:43 
GeneralMy vote of 2 Pin
Petr Pechovic13-Aug-11 2:09
professionalPetr Pechovic13-Aug-11 2:09 
SuggestionHave you heard about SQL injection Pin
GiDEoN198212-Aug-11 4:58
GiDEoN198212-Aug-11 4:58 
GeneralRe: Have you heard about SQL injection Pin
Pascal Ganaye12-Aug-11 5:20
Pascal Ganaye12-Aug-11 5:20 
GeneralRe: Have you heard about SQL injection Pin
Sreedhar Taduri14-Aug-11 18:55
Sreedhar Taduri14-Aug-11 18:55 

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

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