话不多说了,直接上代码。
1.新建一个web页面,并引入相关的js脚本。并放一个textbox控件。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" MaintainScrollPositionOnPostback ="true"%>
<!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">
<script src="js/jquery-1.4.4.min.js" type="text/javascript"></script>
<link href="style/jquery.autocomplete.css" rel="stylesheet" type="text/css" />
<script src="js/jquery.autocomplete.js" type="text/javascript"></script>
<title></title>
<script language="javascript" type ="text/javascript">
function bindAutoComplete() {
$('#txtContent').autocomplete("AutoCompleteHandler.ashx",
{
max: 1000,
delay: 5, minChars: 0,
matchSubset: 1,
cacheLength: 1,
scrollHeight: 200,
highlight: false,
scroll: true,
formatItem: function(data, i, total) {
return data[0].split('*')[0] ; //显示
},
formatMatch: function(data, i, total) {
return data[0].split('*')[0]; //选中
},
formatResult: function(data) {
return data[0].split('*')[0]; //获得的值
},
autoFill: false, maxItemsToShow: 20
});
}
</script>
</head>
<body runat ="server">
<form id="form1" runat="server">
<asp:TextBox ID ="txtContent" runat ="server" onfocus="bindAutoComplete()"></asp:TextBox>
</form>
</body>
</html>
2.AutoCompleteHandler代码
<%@ WebHandler Language="C#" Class="AutoCompleteHandler" %>
using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Linq;
public class AutoCompleteHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string s = context.Request.Params["q"]; //textbox输入的值
string result = GetNum(s);
context .Response .Write (result );
}
public string GetNum(string num)
{
List<string> list = new List<string>();
StringBuilder sBuilder = new StringBuilder();
list .Add("1");
list .Add("12");
list .Add("123");
list .Add("1234");
list .Add("12345");
list .Add("123456");
list .Add("1234567");
list .Add("12345678");
list .Add("123456789");
list .Add("2");
list .Add("23");
var item= from n in list
where n.Contains (num )
select n ;
foreach (string s in item.ToList<string>())
{
sBuilder.Append(s + "*\n");
}
return sBuilder.ToString();
}
public bool IsReusable {
get {
return false;
}
}
}