頁面代碼
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>自動完成查數據表</title></head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" TargetControlID="TextBox1" ServicePath="WebService.asmx"
MinimumPrefixLength="1" ServiceMethod="GetUsers" CompletionSetCount="8" CompletionInterval="10" EnableCaching="true"
runat="server">
</cc1:AutoCompleteExtender>
</form>
</body>
</html>
二web service代碼
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections.Generic; //System.Collections.Generic是List的命名空間
using System.Data.SqlClient;
using System.Web.Script.Services;
/// <summary>
/// WebService 的摘要說明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService] //用於調用web service標簽
public class WebService : System.Web.Services.WebService
{
public WebService() { }
[WebMethod]
public string[] GetUsers(string prefixText, int count) //兩個參數分別是輸入文本跟提示項數
{
//string[] items = new string[count];
List<string> items = new List<string>(count); //泛型(List可以理解成物件或類別的集合,我們可以根據特殊條件在List里找到所需要的值)
SqlConnection myCon = new SqlConnection("Data Source=ITSRV;Initial Catalog=pubs;User ID=newman;Password=newman");//數據庫連接
myCon.Open(); //打開數據庫連接
SqlCommand myCmd = new SqlCommand("select top " + count + " * from authors where au_id like '" + prefixText + "%'", myCon);
SqlDataReader myDR = myCmd.ExecuteReader();
string auid;
while (myDR.Read())
{
auid = myDR["au_id"].ToString().Trim();
items.Add("'" + auid + "'");
}
myCon.Close(); //關閉數據庫連接
return items.ToArray();
}
}