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 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>
    <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>
</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.

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

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

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.

推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架