日期:2014-05-18  浏览次数:20388 次

关于AutoComplete实现输入框提示的问题
下面的代码是个正确的例子,没有错误,实现了在文本框中输入员工姓名的拼音就会弹出相应员工的提示框,
我现在想要实现的是把这个例子替换<select>来使用,但是我不知道怎么记录员工的ID,
就是说我们如果用<select>的话,那么选择好员工后点保存按钮,发送给服务器的是员工ID(<option value=员工ID>员工姓名</option>,
不知道用AutoComplete怎么实现?

default.aspx
C# code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <div>
            <ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="TextBox1" ServiceMethod="GetCompletionList" CompletionSetCount="10" CompletionInterval="500" MinimumPrefixLength="1">
            </ajaxToolkit:AutoCompleteExtender>
        </div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </form>    
</body>
</html>





default.aspx.cs
C# code

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    static SqlConnection conn;
    protected void Page_Load(object sender, EventArgs e)
    {
        conn = new SqlConnection(@"server=.\SQL2000;database=JHCRM;uid=sa;pwd=sa");
    }

    [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] GetCompletionList(string prefixText,int count)
    {        
        conn.Open();
        string sql = "SELECT YGID,YGNAME FROM TEMP_YG WHERE YGPY LIKE '" + prefixText + "%'";
        SqlDataAdapter da = new SqlDataAdapter(sql, conn);
        DataSet ds = new DataSet();
        da.Fill(ds);
        conn.Close();
        int i = 0;
        string[] temp = new string[ds.Tables[0].Rows.Count];
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            temp[i] = dr[1].ToString();
            i++;
        }
        return temp;
    }
}




------解决方案--------------------
AutoComplete所接收的是string数组,如果按照你说的这样,比如:有张三、张四,我想只输入张,就能出来张三、张四,即模糊搜索,但张这个东西并没有ID,那你怎么办呢?应该这个比竟是Textbox,你不能阻止客户输入,也不能阻止客户不选择下拉列表出来的相关字段,而只是输入员工姓名的一部分。



如果想实现你那个功能,可以根据员工姓名 传到服务器后,在进行一次数据库访问,取出ID,不过这样做好像没啥意义。



AutoCompleteExtender使用起来的效率也不是能高,