用AjaxControl Toolkit的autocomplete控件来解决搜索自动匹配.
WebService的代码段为:
public static string[] autoComplete = null;
[WebMethod]
public string[] GetCompletionList(string prefixText, int count)
{
//验证参数是否为空
if (string.IsNullOrEmpty(prefixText) == true || count <= 0) return null;
//判断是否已有数据
if (autoComplete == null)
{
//填充数据ps.这里我用强类型的数据集填充.用其他的数据也行.
DataSet1.AjaxAutoCompleteDataTable dt = new DataSet1.AjaxAutoCompleteDataTable();
DataSet1TableAdapters.AjaxAutoCompleteTableAdapter da = new DataSet1TableAdapters.AjaxAutoCompleteTableAdapter();
da.Fill(dt);
//检测数据是否为空
if (dt.Rows.Count <= 0) return null;
//用一个临时数组存放所有的结果
string[] TempList = new string[dt.Rows.Count];
for (int i = 0; i <TempList.Length;i++ )
{
TempList[i] = dt.Rows[i][dt.CompleteTextColumn].ToString();
}
//排序
Array.Sort(TempList, new CaseInsensitiveComparer());
autoComplete = TempList;
}
////////////////////////////////对结果进行筛选///////////////////////////////////
//用BinarySearch定位起点
int index = Array.BinarySearch(autoComplete, prefixText);
if (index < 0)
{
index = ~index;
}
int march=0;
//配对以prefix开头的选项
for (march; march<count && march < autoComplete.Length - index; march++)
{
if (autoComplete[index + march].StartsWith(prefixText, StringComparison.CurrentCultureIgnoreCase) == false)
{
break;
}
}
//将符合的选项放到新的string[]中然后返回
string[] newArr = new string[march];
Array.Copy(autoComplete, index, newarr, 0, march);
return newArr;
}
ScriptManager指向这个Webservice
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="AutoComplete.asmx" />
</Services>
</asp:ScriptManager>
AutoComplete设置:GetCompletionList为WebServices的方法.AutoComplete.asmx为WebService的文件,TargetControlID是搜索框的文本
<ajaxToolkit:AutoCompleteExtender
ID="AutoCompleteExtender1"
runat="server"
ServiceMethod="GetCompletionList"
EnableCaching="True"
ServicePath="AutoComplete.asmx"
TargetControlID="TextBox1" >
</ajaxToolkit:AutoCompleteExtender>
PS:在WebService里面要加入[System.Web.Script.Services.ScriptService]这属性.