Click here to Skip to main content
15,113,057 members
Articles / Web Development / ASP.NET
Article
Posted 12 Aug 2011

Stats

36.7K views
826 downloads
13 bookmarked

AutoComplete Textbox

Rate me:
Please Sign up or sign in to vote.
3.00/5 (9 votes)
22 Aug 2011CPOL
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)

Share

About the Author

Sreedhar Taduri
Software Developer (Senior) Agility E Services
India India
No Biography provided

Comments and Discussions

 
QuestionThanks Pin
tranquocdung435-Jan-12 18:20
Membertranquocdung435-Jan-12 18:20 
QuestionCode is not working for chrome and firefox browsers Pin
Member 310337316-Nov-11 5:54
MemberMember 310337316-Nov-11 5:54 
GeneralMy vote of 2 Pin
Praveen Meghwal22-Aug-11 22:59
MemberPraveen Meghwal22-Aug-11 22:59 
GeneralMy vote of 5 Pin
mhamad zarif22-Aug-11 22:29
Membermhamad zarif22-Aug-11 22:29 
GeneralMy vote of 3 Pin
mbcrump13-Aug-11 13:10
mentormbcrump13-Aug-11 13:10 
GeneralRe: My vote of 3 Pin
Sreedhar Taduri14-Aug-11 19:57
MemberSreedhar Taduri14-Aug-11 19:57 
GeneralMy vote of 2 Pin
Warrick Procter13-Aug-11 3:43
MemberWarrick Procter13-Aug-11 3:43 
Not an article, a tip/trick. I expect more from an article.
An article is more than a dump of some code, it provides some guidance and some background as to what the code does and why it is useful.
GeneralMy vote of 2 Pin
Petr Pechovic13-Aug-11 3:09
professionalPetr Pechovic13-Aug-11 3:09 
SuggestionHave you heard about SQL injection Pin
GiDEoN198212-Aug-11 5:58
MemberGiDEoN198212-Aug-11 5:58 
GeneralRe: Have you heard about SQL injection Pin
Pascal Ganaye12-Aug-11 6:20
MemberPascal Ganaye12-Aug-11 6:20 
GeneralRe: Have you heard about SQL injection Pin
Sreedhar Taduri14-Aug-11 19:55
MemberSreedhar Taduri14-Aug-11 19: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.