当我们在搜索框输入关键字的时候,Google会自动列出相关关键字提示。用asp.net Ajax AutoCompleteExtender控件实现

运行环境行vs 2008 .net 3.5sp1   需单独安装ajax控件工具集
demo源码下载


    <title>无标题页</title>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" />
        
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" 
            TargetControlID
="TextBox1" ServiceMethod="GetCompletionList"  CompletionSetCount="10" MinimumPrefixLength="2" EnableCaching="true"
            UseContextKey
="True">
        
</cc1:AutoCompleteExtender>

        
    
    
</div>
    
</form>
</body>
</html>

对应的cs代码文件
 _Default : System.Web.UI.Page
{
    [System.Web.Services.WebMethodAttribute(),
    System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] GetCompletionList(string prefixText, int count,
       
string contextKey)
    {
        SqlConnection conn;
        SqlCommand cmd;
        
string cmdString =
           
"Select CompanyName from Customers WHERE CompanyName LIKE '" +
           prefixText 
+ "%'";
        conn 
= new SqlConnection(@"Data Source=.;DataBase=Northwind;UID=sa;PWD=sa;");
        
// Put this string on one line in your code
        cmd = new SqlCommand(cmdString, conn);
        conn.Open();

        SqlDataReader myReader;
        List
<string> returnData = new List<string>();

        myReader 
= cmd.ExecuteReader(CommandBehavior.CloseConnection);

        
while (myReader.Read())
        {
            returnData.Add(myReader[
"CompanyName"].ToString());
        }

        
return returnData.ToArray();
    }

}

相关文章: