1、先打开Access数据库,建立如图所示的表:
2、打开VS新建WebForm1.aspx窗体和WebService1.asmx窗体。
3、在WebService1.asmx后台代码中添加以下方法:
(和SQL连接一样先把[System.Web.Script.Services.ScriptService]的注释撤销)
在WebService1.asmx添加一个getText方法
[WebMethod] public string[] getText(string prefixText, int count) { string[] auto = null; if (string.IsNullOrEmpty(prefixText) == true || count <= 0) return null; if (auto == null) { OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(".\\App_Data\\Text.mdb")); string strsql = "select address from Address where address like '%" + prefixText + "%'"; OleDbCommand cmd = new OleDbCommand(strsql, conn); conn.Open(); OleDbDataReader 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; }
4、在WebForm1.aspx窗体中添加ScriptManager控件、TextBox控件、AutoCompleteExtender控件,源代码如下所示:
WebForm1.aspx源码
<body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server" MinimumPrefixLength="1" TargetControlID="TextBox1" ServiceMethod="getText" ServicePath="~/WebService1.asmx" CompletionSetCount="14" FirstRowSelected="True"> </asp:AutoCompleteExtender> <br /> </form> </body>
5、在浏览器中查看如图所示: