应用.Net自动完成功能,首先需要有AjaxControlToolkit.dll
AjaxControlToolkit.rar
1.工程里添加对该文件的引用
2.前台页面添加内容:
<%@ Register assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" namespace="System.Web.UI" tagprefix="asp" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>
添加文本框
<asp:TextBox ID="txtLB" runat="server" Width="200" CssClass="TextBox" MaxLength="10"></asp:TextBox >
添加AutoCompleteExtender ,当然ScriptManager 也是必须的
<asp:ScriptManager runat="server">
</asp:ScriptManager>
<cc1:AutoCompleteExtender ID="txtLB_AutoCompleteExtender" runat="server" DelimiterCharacters="|" Enabled="True"
MinimumPrefixLength="1" ServiceMethod="GetTextString" ServicePath="WebService.asmx" TargetControlID="txtLB" UseContextKey="True"
CompletionSetCount="30" CompletionInterval="100" >
</cc1:AutoCompleteExtender >
上面属性:TargetControlID就是文本框的ID,CompletionInterval是调用间隔,1000是一秒
ServiceMethod是调用的WebService里的方法 GetTextString
ServicePath是WebService的路径,所以要添加WebService
3.
/// <summary>
///WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService] //不要遗忘掉了取消注释
public class WebService : System.Web.Services.WebService
{
GradeSettingLoader _loader = new GradeSettingLoader();
public WebService()
{
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
private string[] autoCompleteWordList = null;//保存获取的内容
[WebMethod]
public string[] GetTextString(string prefixText, int count)
//string prefixText, int count 两个参数必须原封不动照写,包括大小写也是一样 返回参数只能是字符串数组
//prefixText表示用户输入的前缀,count表示返回的个数
{
if (string.IsNullOrEmpty(prefixText) == true)
return null;
if (autoCompleteWordList == null)
{
DataSet ds = _loader.GetGradeLB();
string[] temp = new string[ds.Tables[0].Rows.Count];//临时数组
int i = 0;
foreach (DataRow dr in ds.Tables[0].Rows)
{
temp[i] = Convert.ToDecimal(dr["INSURANCEGRADE"]).ToString();
i++;
}
Array.Sort(temp, new CaseInsensitiveComparer());
autoCompleteWordList = temp;//临时数组赋值给刚刚前面申明的数组
}
//定位二叉树起点
int index = Array.BinarySearch(autoCompleteWordList, prefixText, new CaseInsensitiveComparer());
if (index < 0)
{
index = ~index;//修复起点
}
//搜索符合条件的数据
int matchCount = 0;
for (matchCount = 0; matchCount < count && matchCount + index < autoCompleteWordList.Length; matchCount++)
{
if (autoCompleteWordList[index + matchCount].StartsWith(prefixText, StringComparison.CurrentCultureIgnoreCase) == false)
{
break;
}
}
//处理搜索结果
string[] matchResultList = new string[matchCount];
if (matchCount > 0)
{
Array.Copy(autoCompleteWordList, index, matchResultList, 0, matchCount);
}
return matchResultList;
}
}
4.注意,WebService里方法返回的是Json数据,即已逗号分隔的,如果数据里本来就有逗号,就比较麻烦了,可以用特殊字符“?“替换常规逗号","。