来自数据库的Ajax autocompleteextender

时间:2010-07-03 10:07:35

标签: c# asp.net mysql ajax autocompleteextender

我想在我的aspx应用程序中创建一个文本框(用于输入名称),该文件框建议来自数据库的Employees名称。

我正在粘贴下面的代码。我正在使用Mysql

Default.aspx:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head runat="server">
    <title>Untitled Page</title>
  </head>
  <body>
    <form id="form1" runat="server">
    <div>
       <asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
       <asp:AutoCompleteExtender ID="TextBox1_AutoCompleteExtender" runat="server" 
                  ServiceMethod="GetCompletionList2" TargetControlID="TextBox1" 
                  UseContextKey="True">
       </asp:AutoCompleteExtender>
    </div>  
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    </form>
  </body>
</html>

Default.aspx.cs:

// here we use a readymade class for database operations to Mysql server
using System;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;


using Gbs.DAL;  // for ..redymade class..

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] GetCompletionList2(string prefixText, int count, string contextKey)
    {
        myDb db = new myDb();// its class in Dal.cs

        string sql = "Select * from empdata Where empname like @prefixText";
        DataTable dt = db.getDataTable(sql);     // method in redymade class
        string[] items = new string[dt.Rows.Count];
        int i = 0;
        foreach (DataRow dr in dt.Rows)
        {
            items.SetValue(dr["empname"].ToString(), i);
            i++;
        }
        return items;
    }

    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {
    }
}

//没有任何错误,程序成功运行

1 个答案:

答案 0 :(得分:0)

AutocompleteExtender需要一个可以从javascript调用的.asmx Web服务。 它不适用于您的Default.aspx。