当我们在搜索框输入关键字的时候,Google会自动列出相关关键字提示。用asp.net Ajax AutoCompleteExtender控件实现
运行环境行vs 2008 .net 3.5sp1 需单独安装ajax控件工具集
demo源码下载
Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!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">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="TextBox1" ServiceMethod="GetCompletionList" CompletionSetCount="10" MinimumPrefixLength="2" EnableCaching="true"
UseContextKey="True">
</cc1:AutoCompleteExtender>
</div>
</form>
</body>
</html>
对应的cs代码文件
Code
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
[System.Web.Services.WebMethodAttribute(),
System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] GetCompletionList(string prefixText, int count,
string contextKey)
{
SqlConnection conn;
SqlCommand cmd;
string cmdString =
"Select CompanyName from Customers WHERE CompanyName LIKE '" +
prefixText + "%'";
conn = new SqlConnection(@"Data Source=.;DataBase=Northwind;UID=sa;PWD=sa;");
// Put this string on one line in your code
cmd = new SqlCommand(cmdString, conn);
conn.Open();
SqlDataReader myReader;
List<string> returnData = new List<string>();
myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (myReader.Read())
{
returnData.Add(myReader["CompanyName"].ToString());
}
return returnData.ToArray();
}
}