完整代码如下,请看:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="combobox测试.WebForm1" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!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:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:TextBox ID="TextBox1" runat="server" Width="300px"></asp:TextBox>
<asp:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server" ServicePath="AutoComplete.asmx"
ServiceMethod="GetPort" TargetControlID="TextBox1" MinimumPrefixLength="1" CompletionSetCount="10"></asp:AutoCompleteExtender>
</div>
</form>
</body>
</html>
其中的 AutoComplete.asmx是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
namespace combobox测试
{
/// <summary>
/// AutoComplete 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public string[] GetData(string prefixText, int count)
{
string[] data = new string[4] { "中国", "中国台湾", "中国香港", "美国" };
return data.Where(p => p.IndexOf(prefixText) >= 0).Take(count).ToArray();
}
[WebMethod]
public string[] GetPort(string prefixText, int count)
{
string connection = "*****";
SqlConnection cn;
DataSet ds = new DataSet();
using (cn = new SqlConnection(connection))
{
cn.Open();
string sql = "******";
SqlDataAdapter adapter = new SqlDataAdapter(sql, cn);
adapter.Fill(ds);
cn.Close();
}
int lenght = ds.Tables[0].Rows.Count;
string[] data = new string[lenght];
for (int i = 0; i < lenght; i++)
{
string temp = ds.Tables[0].Rows[i]["PortName"].ToString() + " " +
ds.Tables[0].Rows[i]["PortCode"].ToString() + " " +
ds.Tables[0].Rows[i]["NationName"].ToString() + " " +
ds.Tables[0].Rows[i]["NationCode"].ToString() + " ";
data[i] = temp;
}
return data;
}
}//end class
}
要提醒的是:
ServiceMethod一定要是: 返回值为string [] 参数一定是 string prefixText 和 int count