(AJAX AutoCompleteExtender cho Textbox trong Asp.net) –  Để gợi ý giúp người sử dụng lựa chọn những từ khóa phù hợp cần tìm kiếm, các Website thường tích hợp chức năng Autocomplete tại Textbox gõ từ khóa. Khi gõ một vài ký tự đầu của từ  khóa, tính năng Autocomplete sẽ liệt kê một danh sách nội dung thỏa mãn từ khóa đã nhập vào. Bài viết dưới đây sẽ hướng dẫn các bạn cách sử dụng AJAX AutoCompleteExtender, mỗi khi gõ từ khóa vào Textbox một danh sách tên khách hàng sẽ xuất hiện để người dùng lựa chọn.

Nghe những bài hát đỉnh nhất về Thấy cô giáo - Nghe trên Youtube



Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



B1: Tạo CSDL Customers trong SQL Server

B2: Tạo Bảng Accounts có cấu trúc phía dưới

STTTên trườngKiểu trườngGhi chú
1AccountIDIntTrường tự tăng
2AccountCodenvarchar(25)
3AccNamenvarchar(250)
4AccAddressnvarchar(250)
5AccPhonenvarchar(50)
6AccFAXnvarchar(50)
7AccEmailnvarchar(50)
8AccWebsitenvarchar(150)
9AccDescnvarchar(1500)
10CreatedDatedatetime
11ModifiedDatedatetime


B3: Nhập dữ liệu cho bảng Accounts


B4: Tạo các stored procedure trong SQL Server

USE [Customers]
GO

CREATE PROCEDURE [dbo].[Pro_Accounts_List]
      @Keyword nvarchar(250),
      @SortField nvarchar(50),
      @SortType nvarchar(10)
AS

declare @strSQL   nvarchar(1000)
declare @strWhere nvarchar(500)
declare @strOrder nvarchar (50)

set @strSQL= 'Select * from Accounts'
set @strWhere =' Where 1=1 '

if @Keyword<>''
      set @strWhere= @strWhere  +' And (AccountCode like N''%' +@Keyword+'%''
            Or AccName like N''%' +@Keyword+'%'' Or AccAddress like N''%' +@Keyword+'%''
            Or AccPhone like N''%' +@Keyword+'%'' Or AccFAX like N''%' +@Keyword+'%''
            Or AccEmail like N''%' +@Keyword+'%'' Or AccWebsite like N''%' +@Keyword+'%'')'

if @SortField='CreatedDate'
      Begin
            set @strOrder =' Order by CreatedDate'
      End
Else
      Begin
            set @strOrder =' Order by AccName'
      End

set @strSQL=@strSQL+@strWhere+@strOrder
print @strSQL
exec sp_executesql @strSQL
Go

Bạn có thể tải về bảng cơ sở dữ liệu SQL bằng cách nhấn vào liên kết tải về dưới đây

B5: Tạo Project trong Microsoft Visual Studio 2010

Trong Visual Studio tạo 1 Class có tên: Utility và nhập đoạn Code phía dưới cho Class này.

Imports System.Data.SqlClient
Imports System.Data

Namespace AJAXAutoCompleteExtender

    Public Class SqlDataProvider

#Region "Membres Prives"

        Shared _IsError As Boolean = False
        Private _connectionString As String

#End Region

#Region "Constructeurs"

        Public Sub New()
            Try
                _connectionString = ConfigurationManager.ConnectionStrings("SiteSqlServer").ConnectionString
                _IsError = False
            Catch ex As Exception
                _IsError = True
            End Try
        End Sub

#End Region

#Region "Proprietes"

        Public ReadOnly Property ConnectionString() As String
            Get
                Return _connectionString
            End Get
        End Property

#End Region

#Region "Functions"

        Public Function FillTable(ByVal sql As StringAs DataTable
            Try
                Dim tb As New DataTable
                Dim adap As New SqlDataAdapter(sql, _connectionString)
                adap.Fill(tb)
                Return tb
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

        Public Function FillTable(ByVal ProcName As StringByVal ParamArray Para() As ObjectParaAs DataTable
            Try
                Dim tb As New DataTable
                Dim adap As New SqlDataAdapter(ProcName, _connectionString)
                adap.SelectCommand.CommandType = CommandType.StoredProcedure
                If Not Para Is Nothing Then
                    For Each p As ObjectPara In Para
                        adap.SelectCommand.Parameters.Add(New SqlParameter(p.Name, p.Value))
                    Next
                End If
                adap.Fill(tb)
                Return tb
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

        Public Function RunSQL(ByVal ProcName As StringByVal ParamArray Para() As ObjectParaAs Object
            Try
                Dim _cnn As New SqlConnection(_connectionString)
                _cnn.Open()

                Dim cmd As New SqlCommand(ProcName, _cnn)
                cmd.CommandType = CommandType.StoredProcedure
                For Each p As ObjectPara In Para
                    cmd.Parameters.Add(New SqlParameter(p.Name, p.Value))
                Next
                Return cmd.ExecuteScalar
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

#End Region

    End Class

    Public Class ObjectPara
        Dim _name As String
        Dim _Value As Object

        Sub New(ByVal Pname As StringByVal PValue As Object)
            _name = Pname
            _Value = PValue
        End Sub

        Public Property Name() As String
            Get
                Return _name
            End Get
            Set(ByVal value As String)
                _name = value
            End Set
        End Property

        Public Property Value() As Object
            Get
                Return _Value
            End Get
            Set(ByVal value As Object)
                _Value = value
            End Set
        End Property

    End Class

Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config

B6: Download thư viện AjaxControlToolkit tại địa chỉ: Download

B7: Giải nén AjaxControlToolkit.Binary.NET4, và References Ajaxcontroltoolkit.dll trong thư mục vừa giải nén vào Project.

B8: Mở file Site.css nhập thêm đoạn Code phía dưới
.CompletionListCssClass
{
    margin : 0px!important;
    background-color : White;
    color : windowtext;
    border : buttonshadow;
    border-width : 1px;
    border-style : solid;
    cursor : 'default';
    overflow : auto;
    font-family:Calibri;
    font-size:12px;
    text-align : left;
    list-style-type : none;
    margin-left:0px;
    padding-left:5px;
    max-height:150px;
    width:auto;
}

B9: Mở file Default.aspxdưới dạng HTML và  bổ xung Control

<%@ PageTitle="AJAX AutoCompleteExtender Example in ASP.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" EnableEventValidation= "false" CodeBehind="Default.aspx.vb"Inherits="AJAXAutoCompleteExtender._Default"%>
<%@ RegisterAssembly="AjaxControlToolkit"Namespace="AjaxControlToolkit"TagPrefix="cc1"%>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1"EnablePageMethods ="true" runat="server">
    </asp:ScriptManager>
    <h1>
        AJAX AutoCompleteExtender Example in ASP.Net
    </h1>
    <br />
    <asp:UpdatePanel ID="updatePanel"runat="server"UpdateMode="Conditional">
        <ContentTemplate>
            <table cellpadding="2"cellspacing="3"width="100%">
                <tr>
                    <td>
                       
                    </td>
                    <tdalign="right">
                        <asp:Label ID="plKeyword" runat="server" Text="Keyword"></asp:Label>
                        <asp:TextBox ID="txtSearch" CssClass="form-control" ToolTip="Enter Keyword" runat="server" width="200px"></asp:TextBox>
                        <asp:ImageButton ID="cmdQuickSearch" runat="server" causesvalidation="false" imageurl="~/images/icon_search.gif"></asp:ImageButton>
                        <cc1:AutoCompleteExtender ServiceMethod="SearchAccounts" MinimumPrefixLength="2"
                            CompletionInterval="100"EnableCaching="false"CompletionSetCount="10"
                            TargetControlID="txtSearch"ID="ucAutoCompleteExtender"CompletionListCssClass="CompletionListCssClass"runat="server"FirstRowSelected="false">
                        </cc1:AutoCompleteExtender>
                    </td>
                </tr>
                <trid="trMessage"runat="server"visible="false">
                    <td colspan="2">
                        <asp:Label ID="lblMessage" runat="server" Text="No Data"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <tdcolspan="2">
                        <asp:GridView ID="grvObject" runat="server" AllowPaging="true" PageSize="8"
                            CssClass="GridStyle"BorderColor="#cbcbcb"BorderStyle="solid"
                            BorderWidth="1"AutoGenerateColumns="false"DataKeyNames="AccountID"width="100%">
                            <AlternatingRowStyleCssClass="GridStyle_AltRowStyle"/>
                            <HeaderStyle CssClass="GridStyle_HeaderStyle"/>
                            <RowStyle CssClass="GridStyle_RowStyle"/>
                            <pagerstyle cssclass="GridStyle_pagination"/>
                            <Columns>
                                <asp:TemplateField HeaderText = "Number">
                                    <ItemStyle HorizontalAlign="Center"Width="2%"></ItemStyle>
                                    <ItemTemplate>
                                        <asp:Label ID="lblRowNumber"Text='<%# Container.DataItemIndex + 1 %>' runat="server"/>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:BoundField ItemStyle-Width="10%"DataField="AccountCode"HeaderText="AccountCode"/>
                                <asp:BoundField ItemStyle-Width="15%"DataField="AccName"HeaderText="AccountName"/>
                                <asp:BoundField ItemStyle-Width="10%"DataField="AccPhone"HeaderText="Phone"/>
                                <asp:BoundField ItemStyle-Width="10%"DataField="AccFAX"HeaderText="FAX"/>
                                <asp:BoundField ItemStyle-Width="15%"DataField="AccEmail"HeaderText="Email"/>                            
                            </Columns>                              
                        </asp:GridView>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

B10: Viết Code cho file Default.aspx
C# Code
//Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Diagnostics;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Web.Script.Services;
using AjaxControlToolkit;

namespace AJAXAutoCompleteExtender
{
    public partial class _Default : System.Web.UI.Page
    {

        #region"WebServices"

        [WebMethod()]
        [ScriptMethod()]
        public static List<string> SearchAccounts(string prefixText, int count)
        {
            DataTable objBind = newDataTable();
            List<string> Accounts = new List<string>();

            objBind = BindData(prefixText);

            if (objBind != null)
            {
                if (objBind.Rows.Count > 0)
                {
                    foreach (DataRowrow in objBind.Rows)
                    {
                        Accounts.Add(row["AccName"].ToString());
                    }
                }
            }
            return Accounts;
        }

        #endregion

        #region"Bind Data"

        private void BindAccount()
        {
            DataTable objBind = newDataTable();
            objBind = BindData(txtSearch.Text);

            if (objBind != null)
            {
                if (objBind.Rows.Count > 0)
                {
                    grvObject.DataSource = objBind;
                    grvObject.DataBind();
                    trMessage.Visible = false;
                    grvObject.Visible = true;
                }
                else
                {
                    trMessage.Visible = true;
                    grvObject.Visible = false;
                }
                updatePanel.Update();
            }
        }

        public static DataTable BindData(stringKeyword)
        {
            SqlDataProvider objSQL = newSqlDataProvider();
            DataTable objBind = objSQL.FillTable("Pro_Accounts_List", new ObjectPara("@Keyword", Keyword.Trim()), new ObjectPara("@SortField", "CreatedDate"), new ObjectPara("@SortType", "DESC"));
            return objBind;
        }

        #endregion

        #region"GridView Methods"

        protected voidgrvObject_PageIndexChanging(object sender, System.Web.UI.WebControls.GridViewPageEventArgse)
        {
            grvObject.PageIndex = e.NewPageIndex;
            BindAccount();
        }

        #endregion

        #region"Event Handles"

        protected voidPage_Load(object sender, System.EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    //Default Submit Button
                    Page.Form.DefaultButton = cmdQuickSearch.UniqueID;
                    BindAccount();
                }
            }
            catch
            {
            }
        }

        protected voidcmdQuickSearch_Click(object sender, System.EventArgs e)
        {
            BindAccount();
        }

        #endregion

    }
}

VB.NET Code

Imports System.Web.Services
Imports System.Web.Script.Services
Imports System.Collections.Generic
Imports AjaxControlToolkit

Namespace AJAXAutoCompleteExtender

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "WebServices"

        <WebMethod()> _
        <ScriptMethod()> _
        Public Shared Function SearchAccounts(ByValprefixText As String, ByVal count As Integer) As List(Of String)
            Dim objBind As New DataTable
            Dim Accounts As List(Of String) = New List(Of String)

            objBind = BindData(prefixText)

            If Not objBind Is Nothing Then
                If objBind.Rows.Count > 0 Then
                    For Eachrow As DataRowIn objBind.Rows
                        Accounts.Add(row("AccName").ToString)
                    Next
                End If
            End If
            Return Accounts
        End Function

#End Region

#Region "Bind Data"

        Private SubBindAccount()
            Dim objBind As New DataTable
            objBind = BindData(txtSearch.Text)

            If Not objBind Is Nothing Then
                If objBind.Rows.Count > 0 Then
                    grvObject.DataSource = objBind
                    grvObject.DataBind()
                    trMessage.Visible = False
                    grvObject.Visible = True
                Else
                    trMessage.Visible = True
                    grvObject.Visible = False
                End If
                updatePanel.Update()
            End If
        End Sub

        Public Shared Function BindData(ByValKeyword As String) As DataTable
            Dim objSQL As New SqlDataProvider
            Dim objBind As DataTable = objSQL.FillTable("Pro_Accounts_List", New ObjectPara("@Keyword", Keyword.Trim), _
                                                                          New ObjectPara("@SortField", "CreatedDate"), _
                                                                          New ObjectPara("@SortType", "DESC"))
            Return objBind
        End Function

#End Region

#Region "GridView Methods"

        Private SubgrvObject_PageIndexChanging(ByVal sender As Object, ByVal e AsSystem.Web.UI.WebControls.GridViewPageEventArgs) Handles grvObject.PageIndexChanging
            grvObject.PageIndex = e.NewPageIndex
            BindAccount()
        End Sub

#End Region

#Region "Event Handles"

        Protected SubPage_Load(ByVal sender AsObject, ByVal e As System.EventArgs) Handles Me.Load
            Try
                If Page.IsPostBack = False Then
                    'Default Submit Button
                    Page.Form.DefaultButton = cmdQuickSearch.UniqueID
                    BindAccount()
                End If
            Catch ex As Exception

            End Try
        End Sub

        Private SubcmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlescmdQuickSearch.Click
            BindAccount()
        End Sub

#End Region

    End Class

End Namespace

Bây giờ chạy Project bạn sẽ có kết quả như ảnh phía dưới.

Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



Chúc các bạn thành công!

Quang Bình

0 comments Blogger 0 Facebook

Post a Comment

 
lập trình đốt nét © 2013. All Rights Reserved. Powered by Blogger
Top