1、打开SQL2008 新建数据库ajax;
2、新建表Adress,并编辑相应的数据。创建后如下图所示:
3、打开vs创建新项目,并添加相应的web窗体(WebForm1.aspx)和web服务器窗体(WebService1.asmx);
4、在WebService1.asmx添加下面的方法:
在此之前把 [System.Web.Script.Services.ScriptService]撤销注释。
在WebService1.asmx添加一个方法
[WebMethod] [System.Web.Script.Services.ScriptMethod] public string[] GetSearch(string prefixText, int count) { string[] auto = null; if (string.IsNullOrEmpty(prefixText) == true || count <= 0) return null; if (auto == null) { SqlConnection conn = new SqlConnection("server=.;database=ajax;integrated security=true"); string strsql = "select adress from Adress where adress like '%" + prefixText + "%'"; SqlCommand cmd = new SqlCommand(strsql, conn); conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); ArrayList list = new ArrayList(); while (dr.Read()) { list.Add(dr[0].ToString()); } dr.Close(); string[] temp = new string[list.Count]; int i = 0; foreach (string s in list) { temp[i++] = s; } auto = temp; } return auto; }
5、在WebForm1.aspx窗体上添加ToolkitScriptManager控件、TextBox控件、ToolkitScriptManager控件。源代码如下:
源代码
<body> <form id="form1" runat="server"> <div> <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" ScriptMode="Release"> </asp:ToolkitScriptManager> </div> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> </asp:UpdatePanel> <asp:TextBox ID="TextBox1" runat="server"> </asp:TextBox> <asp:AutoCompleteExtender ID="ToolkitScriptManager1" runat="server" MinimumPrefixLength="1" TargetControlID="TextBox1" ServiceMethod="GetSearch" ServicePath="~/WebService1.asmx" CompletionSetCount="10" FirstRowSelected="true"> </asp:AutoCompleteExtender> </form> </body>
6、运行输入“河”字出现如图所示: