65.9K
CodeProject 正在变化。 阅读更多。
Home

带数据库和 AjaxControlToolkit 的自动完成

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.79/5 (101投票s)

2011年5月24日

Ms-PL

4分钟阅读

viewsIcon

661303

downloadIcon

49144

这是一个非常简单的代码,可以创建一个带数据库的自动完成组合框。

Sample Image - maximum width is 600 pixels

引言

这是一个非常简单的代码,可以创建一个带数据库的自动完成组合框。

它很有用。首先,您不必了解 Ajax 函数,只需在 CodePlex 上下载 AJAX Control Toolkit 并跟着我做,然后尽情享用。此外,当有许多行时,您可以在文本框中输入部分单词,然后它会提供所有与您输入的单词相似的单词。

背景:什么是 AjaxControlToolkit?

ASP.NET AJAX Control Toolkit 是一个开源项目,构建在 Microsoft ASP.NET AJAX 框架之上,包含 30 多个控件,使您能够轻松创建丰富的交互式网页。如果您想了解更多信息,请访问此链接

Using the Code

第一步,您必须从.NET 3.5 的此处.NET 4.0 的此处下载 AjaxControlToolkit。

您必须到此处下载 ajaxcontroltoolkit,然后将 ajaxcontroltoolkit 复制并粘贴到Bin文件夹中,右键单击解决方案,选择“添加引用”,在“浏览”选项卡中双击Bin文件夹,然后双击 ajaxcontroltoolkit,接着在“生成”菜单中单击“重新生成”。

DataBase

新查询

CREATE TABLE [dbo].[tblCustomer](
	    [CompanyName] [nvarchar](500) NULL,
	    [ID] [int] IDENTITY(1,1) NOT NULL
        ) ON [PRIMARY]

insert into dbo.tblCustomer(CompanyName) values('calemard')
insert into dbo.tblCustomer(CompanyName) values('dantherm')
insert into dbo.tblCustomer(CompanyName) values('dango dienenthal')
insert into dbo.tblCustomer(CompanyName) values('daewoo')
insert into dbo.tblCustomer(CompanyName) values('daim engineering')

Visual Studio 2008 - .NET 3.5:创建一个名为 AutoComplete 的网站,创建一个名为AutoComplete.aspx的 Web 窗体,在 HTML 视图中,编写此代码。
但 C# 和 VB 在这部分有一个小区别。

  1. 下面的代码是为 C# 编码人员准备的。
  2. 如果您是 VB 编码人员,请修改页面标签中的 2 个部分
    1. 一:将 language=VB设为正确
    2. 二:将 CodeFile="AutoComplete.aspx.vb"设为正确
<%@ Page Language="C#" AutoEventWireup="false"
         CodeFile="AutoComplete.aspx.cs" Inherits="AutoComplete" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
         TagPrefix="ajaxToolkit" %>
<!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>AutoComplete</title>
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<ajaxToolkit:ToolkitScriptManager  ID="ScriptManager1" runat="server">
</ajaxToolkit:ToolkitScriptManager>
<ajaxToolkit:AutoCompleteExtender ID="autoComplete1" runat="server"
  EnableCaching="true"
  BehaviorID="AutoCompleteEx"
  MinimumPrefixLength="2"
  TargetControlID="myTextBox"
  ServicePath="AutoComplete.asmx"
  ServiceMethod="GetCompletionList" 
  CompletionInterval="1000"  
  CompletionSetCount="20"
  CompletionListCssClass="autocomplete_completionListElement"
  CompletionListItemCssClass="autocomplete_listItem"
  CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
  DelimiterCharacters=";, :"
  ShowOnlyCurrentWordInCompletionListItem="true">
  <Animations>
  <OnShow>
  <Sequence>
  <%-- Make the completion list transparent and then show it --%>
  <OpacityAction Opacity="0" />
  <HideAction Visible="true" />

  <%--Cache the original size of the completion list the first time
    the animation is played and then set it to zero --%>
  <ScriptAction Script="// Cache the size and setup the initial size
                                var behavior = $find('AutoCompleteEx');
                                if (!behavior._height) {
                                    var target = behavior.get_completionList();
                                    behavior._height = target.offsetHeight - 2;
                                    target.style.height = '0px';
                                }" />
  <%-- Expand from 0px to the appropriate size while fading in --%>
  <Parallel Duration=".4">
  <FadeIn />
  <Length PropertyKey="height" StartValue="0" 
	EndValueScript="$find('AutoCompleteEx')._height" />
  </Parallel>
  </Sequence>
  </OnShow>
  <OnHide>
  <%-- Collapse down to 0px and fade out --%>
  <Parallel Duration=".4">
  <FadeOut />
  <Length PropertyKey="height" StartValueScript=
	"$find('AutoCompleteEx')._height" EndValue="0" />
  </Parallel>
  </OnHide>
  </Animations>
  </ajaxToolkit:AutoCompleteExtender>
<asp:TextBox ID="myTextBox" autocomplete ="off" runat="server"></asp:TextBox>

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

样式表 (CSS 文件)

  • 创建样式表:解决方案 > 右键单击 > 添加新项 > Web 服务 >
  • 名称:StyleSheet.css
  • 语言:Visual Basic 或 C#
  • 转到 > StyleSheet.css (文件) > Ctrl+A (全选) > 删除
  • 转到以下部分 (下方) > 选择此代码 > Ctrl+C >
  • 转到StyleSheet.css (文件) > Ctrl+V (粘贴)
/*AutoComplete flyout */
.autocomplete_completionListElement
{
    margin : 0px!important ;
    background-color : inherit ;
    color : windowtext ;
    border : buttonshadow ;
    border-width : 1px ;
    border-style : solid ;
    cursor : 'default' ;
    overflow : auto ;
    height : 200px ;
    font-family : Tahoma ;
    font-size : small ;
    text-align : left ;
    list-style-type : none ;
    }
/* AutoComplete highlighted item */
.autocomplete_highlightedListItem
   {
    background-color : #ffff99 ;
    color : black ;
    padding : 1px ;
    }

    /* AutoComplete item */
.autocomplete_listItem
    {
    background-color : window ;
    color : windowtext ;
    padding : 1px ;
   }

对于 VB

  • 创建 Web 服务:解决方案 > 右键单击 > 添加新项 > Web 服务 >
  • 名称:AutoComplete.asmx
  • 语言:Visual Basic
  • 转到 > App_Code > AutoComplete.vb
' (c) Copyright Microsoft Corporation.
' This source is subject to the Microsoft Public License.
' See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
' All other rights reserved.
Imports System
Imports System.Collections
Imports System.Linq
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Xml.Linq
Imports System.Collections.Generic
Imports System.Data
Imports System.Data.SqlClient

' To allow this Web Service to be called from script, using ASP.NET AJAX, 
' uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
Public Class AutoComplete
    Inherits System.Web.Services.WebService
    Dim cn As New SqlClient.SqlConnection()
    Dim ds As New DataSet
    Dim dt As New DataTable
<WebMethod()> _
Public Function GetCompletionList(ByVal prefixText As String, _
	ByVal count As Integer) As String()

        'ADO.Net
        Dim strCn As String = _
		"data source=.;Initial Catalog=MyDB;Integrated Security=True"
        cn.ConnectionString = strCn
        Dim cmd As New SqlClient.SqlCommand
        cmd.Connection = cn
        cmd.CommandType = CommandType.Text
        'Compare String From Textbox(prefixText) 
        'AND String From Column in DataBase(CompanyName)
        'If String from DataBase is equal to String from TextBox(prefixText) 
        'then add it to return ItemList
        '-----I defined a parameter instead of passing value 
        'directly to prevent SQL injection--------'
        cmd.CommandText = "select * from tblCustomer Where CompanyName like @myParameter"
        cmd.Parameters.AddWithValue("@myParameter", "%" + prefixText + "%")

        Try
            cn.Open()
            cmd.ExecuteNonQuery()
            Dim da As New SqlDataAdapter(cmd)
            da.Fill(ds)
        Catch ex As Exception
        Finally
            cn.Close()
        End Try

        dt = ds.Tables(0)

        'Then return List of string(txtItems) as result

        Dim txtItems As New List(Of String)
        Dim dbValues As String

        For Each row As DataRow In dt.Rows

            ''String From DataBase(dbValues)
            dbValues = row("CompanyName").ToString()
            dbValues = dbValues.ToLower()
            txtItems.Add(dbValues)

        Next

        Return txtItems.ToArray()

    End Function

End Class

对于 C#

  • Web 服务:解决方案 > 右键单击 > 添加新项 > Web 服务 >
  • 名称:AutoComplete.asmx
  • 语言:C#
  • 转到 > App_Code > AutoComplete.cs
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License.
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
// All other rights reserved.
using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

///<summary>
/// Summary description for AutoComplete
///</summary>

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, 
// uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class AutoComplete : System.Web.Services.WebService {

    public AutoComplete () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    public string[] GetCompletionList(string prefixText, int count)
    {
        //ADO.Net
        SqlConnection cn =new SqlConnection();
        DataSet ds = new DataSet();
        DataTable  dt = new DataTable();
        String strCn = "data source=.;Initial Catalog=MyDB;Integrated Security=True";
        cn.ConnectionString = strCn;
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = cn;
        cmd.CommandType = CommandType.Text;
        //Compare String From Textbox(prefixText) AND String From 
        //Column in DataBase(CompanyName)
        //If String from DataBase is equal to String from TextBox(prefixText) 
        //then add it to return ItemList
        //-----I defined a parameter instead of passing value directly to 
        //prevent SQL injection--------//
        cmd.CommandText = "select * from tblCustomer Where CompanyName like @myParameter";
        cmd.Parameters.AddWithValue("@myParameter", "%" + prefixText + "%");

        try
        {
            cn.Open();
            cmd.ExecuteNonQuery();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);
        }
        catch
        {
        }
        finally
        {
            cn.Close();
        }
        dt = ds.Tables[0];

	    //Then return List of string(txtItems) as result
        List<string> txtItems =new List<string>();
        String  dbValues;

        foreach (DataRow row  in dt.Rows)
        {
             //String From DataBase(dbValues)
            dbValues = row["CompanyName"].ToString();
            dbValues = dbValues.ToLower();
            txtItems.Add(dbValues);
        }

        return txtItems.ToArray();
    }
}

摘要

GetCompletionList是一个接收 2 个参数的函数,prefixText作为stringcount作为int

当您输入一些字符时,它们会保存在prefixText中,您输入的字符数量会保存在count中。最后,函数返回string列表 (它们与您输入的字符相似),这些列表是通过以下方式获得的:

我在 ADO.NET 部分写了一些代码,这些行已通过prefixText进行过滤,它们与您在文本框中键入的字符相似。
此外,我定义了一个参数而不是直接传递值,以防止 SQL 注入。

我创建了一个List<string>类型的txtItems,我们可以将想要保存的单词保存在其中。然后在一个foreach循环中,我将它们转换为tolower,将这些值添加到我的结果值 (txtItems) 中,最后返回txtItems

一步一步尝试

  1. 请访问.NET 3.5 的此处.NET 4.0 的此处并下载AjaxControlToolkit文件。
  2. 将“AjaxControlToolkit.Dll”文件夹及其所有依赖项 (共 18 个对象) 复制到您的网站Bin文件夹 (C:\AutoComplete\Bin)。
  3. 右键单击解决方案,选择“刷新”,然后再次右键单击并单击“添加引用”,在“浏览”选项卡中双击Bin文件夹,然后双击 ajaxcontroltoolkit,在“生成”菜单中单击“重新生成”。
  4. 创建如上所示的数据库和表,并添加一些包含常见单词的行。
  5. 创建 Web 窗体并命名为:“AutoComplete.aspx”。在 HTML 视图中,编写一些如上的代码。(这应该与我的代码完全一致,因为这部分区分大小写)。
  6. 创建 Web 服务
    解决方案 > 右键单击 > 添加新项 > Web 服务 > 名称:AutoComplete.asmx 语言:C# 或 VB
    转到 > App_Code > AutoComplete.cs
  7. 为了获得一些动画效果,我添加了样式表,使用它以提高用户友好性。
  8. 如果您是 VB 编码人员,请使用 VB 示例,否则使用 C# 示例。
  9. 运行程序,在文本框中输入包含 2 个或更多字符的单词,例如da,您将看到一个与您输入的字符相似的单词列表。

反馈

请随时对本文提出反馈意见;很高兴看到您对这些代码的评论和投票。如果您有任何问题,请随时在此处提问。

© . All rights reserved.