使用ajaxToolkit组件实现类型google,百度下拉框匹配功能
效果图如下,数据库连接的是pubs的authors表
1. 要使用ajaxToolkit组件首先要添加AjaxControlToolkit.dll,并在每个页面顶部注册该组件(Page下面)
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
2. 然后在源页面中添加下面代码,用于调用查询数据的服务
代码
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<ajaxToolkit:AutoCompleteExtender runat="server" ID="AutoCompleteSearch"
MinimumPrefixLength="1" TargetControlID="SearchText"
ServicePath="AutoCompleteService.asmx"
ServiceMethod="GetSearchTerms" EnableViewState="False"></ajaxToolkit:AutoCompleteExtender>
<asp:TextBox ID="SearchText" Width="150px" runat="server" />
</div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<ajaxToolkit:AutoCompleteExtender runat="server" ID="AutoCompleteSearch"
MinimumPrefixLength="1" TargetControlID="SearchText"
ServicePath="AutoCompleteService.asmx"
ServiceMethod="GetSearchTerms" EnableViewState="False"></ajaxToolkit:AutoCompleteExtender>
<asp:TextBox ID="SearchText" Width="150px" runat="server" />
</div>
其中属性的含义分别为:
MinimumPrefixLength:输入第几个字符时开始匹配
ServicePath: 服务文件的路径
ServiceMethod: 调用的服务方法
3. 服务类的源码,查询的是pubs数据库
代码
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class AutoCompleteService : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod]
public string[] GetSearchTerms(string prefixText, int count)
{
SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=pubs;Persist Security Info=True;User ID=sa;Password=123;");
SqlCommand cmd = new SqlCommand(
"SELECT DISTINCT au_lname FROM authors WHERE au_lname like @term", cn);
cmd.Parameters.AddWithValue("nrows", count);
cmd.Parameters.AddWithValue("term", prefixText + "%");
List<string> suggestions = new List<string>();
cn.Open();
using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
while (dr.Read())
suggestions.Add(dr[0].ToString());
}
return suggestions.ToArray();
}
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class AutoCompleteService : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod]
public string[] GetSearchTerms(string prefixText, int count)
{
SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=pubs;Persist Security Info=True;User ID=sa;Password=123;");
SqlCommand cmd = new SqlCommand(
"SELECT DISTINCT au_lname FROM authors WHERE au_lname like @term", cn);
cmd.Parameters.AddWithValue("nrows", count);
cmd.Parameters.AddWithValue("term", prefixText + "%");
List<string> suggestions = new List<string>();
cn.Open();
using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
while (dr.Read())
suggestions.Add(dr[0].ToString());
}
return suggestions.ToArray();
}
完整源码和AjaxControlToolkit.dll请从群中下载:74085440