AutoComplete+数据库,自动完成功能

AutoComplete控件的作用是根据用户在文本框输入的字符而做出相应的提示效果。

例如GOOGLE搜索提示功能。
属性列表:
TargetControlID:要实现提示功能的控件
ServicePath:WEB服务的路径
ServiceMethod:调用数据使用的方法
CompletionSetCount:提示数据的行数
MinimumPrefixLength:用户输入多少字母才出现提示效果
CompletionInterval:从服务器获取数据的时间间隔,单位为毫秒
Enabled:是否启用自动完成功能,默认为TRUE
EnableCaching:是否启用缓存

实例解析一、读取数据库实现自动完成功能
autocomplete表:ID,NAME两个字段。
Default.aspx代码如下:

 1 <head runat="server">
 2     <title>AutoComplete的使用</title>
 3 </head>
 4 <body>
 5     <form id="form1" runat="server">
 6     <div>
 7         <asp:ScriptManager ID="ScriptManager1" runat="server">
 8         </asp:ScriptManager>    
 9     </div>
10         <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
11         <cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="TextBox1" ServicePath="WebServiceAutoComplete.asmx" ServiceMethod="GetCompleteDepart" CompletionSetCount="2" MinimumPrefixLength="1"
12          CompletionInterval="1000">
13         </cc1:AutoCompleteExtender>
14     </form>
15 </body>

WebServiceAutoComplete.asmx.cs文件代码如下:
 

 1 using System;
 2 using System.Web;
 3 using System.Collections;
 4 using System.Web.Services;
 5 using System.Web.Services.Protocols;
 6 using System.Data;
 7 using System.Data.SqlClient;
 8 using System.Configuration;
 9 ..
10 ..
11 [System.Web.Script.Services.ScriptService]
12 public class WebServiceAutoComplete : System.Web.Services.WebService {
13 
14 ..
15 ..
16     //定义数组
17     private static string[] autoCompleteWordList = null;
18     [WebMethod]
19     public string[] GetCompleteDepart(string prefixText, int count)
20     {
21         //如果数组为空
22         if (autoCompleteWordList == null)
23         {
24             DAL.DB DBOperator = new DAL.DB();
25             DataSet ds = DBOperator.GetDs("select name from autocomplete where name like '"+prefixText+"%' order by name");
26             //填充数组
27             string[] temp=new string[ds.Tables[0].Rows.Count];
28             int i = 0;
29             foreach (DataRow dr in ds.Tables[0].Rows)
30             {
31                 temp[i] = dr["name"].ToString();
32                 i++;
33             }
34             //将临时数组的内容赋给返回数组
35             autoCompleteWordList = temp; 
36         }
37         string[] returnValue = new string[count];
38         returnValue = autoCompleteWordList;
39         //返回
40         return returnValue;
41     }    
42 }


 

原文地址:https://www.cnblogs.com/dekevin/p/2471840.html