News Ticker

Menu

Sử dụng AJAX Slider Extender cho Paging Gridview trong Asp.net

(Tạo Paging Gridview bằng AJAX Slider Extender) – Có nhiều cách để phân trang cho Gridview như sử dụng chức năng có sẵn trong Gridview hoặc xây dựng Control riêng để xử lý công việc này. Để có thêm lựa chọn trong việc phân trang cho Gridview, hôm nay thủ thuật lập trình sẽ giới thiệu với các bạn 1 cách nữa, đó là sử dụng AJAX Slider Extender.

Xem những Video hay dành cho thiếu nhi - Nghe trên Youtube



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



B1: Download CSDL Northwind

B2Bổ xung thêm stored procedure trong SQL Server

USE [Northwind]
GO

CREATE PROCEDURE [dbo].[Pro_Customers_List]
      @Keyword nvarchar(250)
AS

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

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

if @Keyword<>''
      set @strWhere= @strWhere  +' And (CompanyName like N''%' +@Keyword+'%''
            Or ContactName like N''%' +@Keyword+'%'' Or ContactTitle like N''%' +@Keyword+'%''
            Or Address like N''%' +@Keyword+'%'' Or City like N''%' +@Keyword+'%''
            Or Region like N''%' +@Keyword+'%'' Or PostalCode like N''%' +@Keyword+'%'')'

set @strOrder =' Order by CompanyName'

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

B3: 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.

Namespace PagingInGridViewUsingSliderExtender

    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 String) As 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 String, ByVal ParamArray Para() As ObjectPara) As 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

#End Region

    End Class

    Public Class ObjectPara
        Dim _name As String
        Dim _Value As Object

        Sub New(ByVal Pname As String, ByVal 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

End Namespace

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

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

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

- B6: Download các file ảnh tại đây, Copy các ảnh vào thư mục Images của Project.


- B7: Mở file Default.aspxdưới dạng HTML và  nhập mã HTML

<%@ Page Title="Paging in GridView using AJAX SliderExtender in ASP.Net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" EnableEventValidation= "false" CodeBehind="Default.aspx.vb" Inherits="PagingInGridViewUsingSliderExtender._Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" EnablePageMethods = "true" runat="server">
    </asp:ScriptManager>
    <h3>
        Paging in GridView using AJAX SliderExtender in ASP.Net
    </h3>
    <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table cellpadding="2" cellspacing="3" width="100%">
                <tr>
                    <td>
                       
                    </td>
                    <td align="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>
                    </td>
                </tr>
                <tr id="trMessage" runat="server" visible="false">
                    <td colspan="2">
                        <asp:Label ID="lblMessage" runat="server" Text="No Data"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:GridView ID="grvObject" runat="server" AllowPaging="true" PageSize="8"
                            CssClass="GridStyle" BorderColor="#cbcbcb" BorderStyle="solid"
                            BorderWidth="1" AutoGenerateColumns="false" DataKeyNames="CustomerID" width="100%">
                            <AlternatingRowStyle CssClass="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="18%" DataField="CompanyName" HeaderText="CompanyName" />
                                <asp:BoundField ItemStyle-Width="15%" DataField="ContactName" HeaderText="AccountName" />
                                <asp:BoundField ItemStyle-Width="12%" DataField="ContactTitle" HeaderText="ContactTitle" />                     
                                <asp:BoundField ItemStyle-Width="12%" DataField="Phone" HeaderText="Phone" />      
                                <asp:BoundField ItemStyle-Width="12%" DataField="Fax" HeaderText="Fax" />     
                            </Columns>  
                            <PagerTemplate>
                                <div>
                                    <table border="0" cellpadding="0" cellspacing="0" width="100%" runat="server">
                                        <tr>
                                            <td align="left" style="width: 2px;">
                                                &nbsp;
                                            </td>
                                            <td align="left" style="width: 10px;">
                                                <asp:ImageButton ID="cmdFirst" runat="server" CommandName="First" ImageUrl="~/Images/first.gif" />
                                            </td>
                                            <td align="left" style="width: 10px;">
                                                <asp:ImageButton ID="cmdPrev" runat="server" CommandName="Prev" ImageUrl="~/Images/Prev.gif" />
                                            </td>
                                            <td align="center" style="width: 150px;">
                                               <asp:TextBox ID="txtSlider" runat="server" AutoPostBack="True"
                                                    Text='<%# grvObject.PageIndex + 1 %>' OnTextChanged="txtSlider_Changed" Width="200px"></asp:TextBox>
                                                <cc1:SliderExtender ID="ucSliderExtender" runat="server" Orientation="Horizontal"
                                                    TargetControlID="txtSlider" Minimum="1" Steps='<%# grvObject.PageCount %>'
                                                    Maximum='<%# grvObject.PageCount %>'></cc1:SliderExtender>
                                            </td>
                                            <td align="left" style="width: 10px;">
                                                <asp:ImageButton ID="cmdNext" runat="server" CommandName="Next" ImageUrl="~/Images/next.gif" />
                                            </td>
                                            <td align="left" style="width: 10px;">
                                                <asp:ImageButton ID="cmdLast" runat="server" CommandName="Last" ImageUrl="~/Images/last.gif" />
                                            </td>
                                            <td align="right" style="padding-right: 25px" class="PageNumber">
                                                <asp:Label ID="lblPage" runat="server" Text='<%# "Page " & (grvObject.PageIndex + 1) & " of " & grvObject.PageCount %>' />
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                            </PagerTemplate>                              
                        </asp:GridView>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

B12: 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.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Diagnostics;

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

        #region "Bind Data"

        private void BindCustomers()
        {
            DataTable objBind = new DataTable();
            int iTotal = 0;
            objBind = BindData();

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

        private DataTable BindData()
        {
            SqlDataProvider objSQL = new SqlDataProvider();
            DataTable objBind = objSQL.FillTable("Pro_Customers_List", new ObjectPara("@Keyword", txtSearch.Text));
            return objBind;
        }

        #endregion

        #region "GridView Methods"

        protected void grvObject_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
        {
            if (e.CommandName == "First")
            {
                grvObject.PageIndex = 0;
            }
            else if (e.CommandName == "Prev")
            {
                if (grvObject.PageIndex > 0)
                {
                    grvObject.PageIndex = grvObject.PageIndex - 1;
                }
            }
            else if (e.CommandName == "Next")
            {
                if (grvObject.PageIndex < grvObject.PageCount - 1)
                {
                    grvObject.PageIndex = grvObject.PageIndex + 1;
                }
            }
            else if (e.CommandName == "Last")
            {
                grvObject.PageIndex = grvObject.PageCount - 1;
            }
            BindCustomers();
        }

        protected void txtSlider_Changed(object sender, EventArgs e)
        {
            TextBox txtCurrentPage = sender as TextBox;
            GridViewRow rowPager = grvObject.BottomPagerRow;
            if (rowPager != null)
            {
                TextBox txtSlide = (TextBox)rowPager.Cells[0].FindControl("txtSlider");
                grvObject.PageIndex = Int32.Parse(txtSlide.Text) - 1;
                BindCustomers();
            }
        }

        #endregion

        #region "Event Handles"

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

        protected void cmdQuickSearch_Click(object sender, System.EventArgs e)
        {
            BindCustomers();
        }

        #endregion
    }
}

VB.NET Code
Namespace PagingInGridViewUsingSliderExtender

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Bind Data"

        Private Sub BindCustomers()
            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(ByVal Keyword As String) As DataTable
            Dim objSQL As New SqlDataProvider
            Dim objBind As DataTable = objSQL.FillTable("Pro_Customers_List", New ObjectPara("@Keyword", Keyword.Trim))
            Return objBind
        End Function

#End Region

#Region "GridView Methods"

        Private Sub grvObject_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grvObject.RowCommand
            If e.CommandName = "First" Then
                grvObject.PageIndex = 0
            ElseIf e.CommandName = "Prev" Then
                If grvObject.PageIndex > 0 Then
                    grvObject.PageIndex = grvObject.PageIndex - 1
                End If
            ElseIf e.CommandName = "Next" Then
                If grvObject.PageIndex < grvObject.PageCount - 1 Then
                    grvObject.PageIndex = grvObject.PageIndex + 1
                End If
            ElseIf e.CommandName = "Last" Then
                grvObject.PageIndex = grvObject.PageCount - 1
            End If
            BindCustomers()
        End Sub

        Protected Sub txtSlider_Changed(ByVal sender As Object, ByVal e As EventArgs)
            Dim txtCurrentPage As TextBox = TryCast(sender, TextBox)
            Dim rowPager As GridViewRow = grvObject.BottomPagerRow
            If Not rowPager Is Nothing Then
                Dim txtSlide As TextBox = CType(rowPager.Cells(0).FindControl("txtSlider"), TextBox)
                grvObject.PageIndex = Int32.Parse(txtSlide.Text) - 1
                BindCustomers()
            End If
        End Sub

#End Region

#Region "Event Handles"

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

            End Try
        End Sub

        Private Sub cmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdQuickSearch.Click
            BindCustomers()
        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

Share This:

Mỗi bài viết đều là công sức và thời gian của tác giả ví vậy tác giả chỉ có một mong muốn duy nhất nếu ai đó có Copy thì xin hãy ghi rõ nguồn và thông tin tác giả ở cuối mỗi bài viết.
Xin cảm ơn!

No Comment to " Sử dụng AJAX Slider Extender cho Paging Gridview trong Asp.net "

  • To add an Emoticons Show Icons
  • To add code Use [pre]code here[/pre]
  • To add an Image Use [img]IMAGE-URL-HERE[/img]
  • To add Youtube video just paste a video link like http://www.youtube.com/watch?v=0x_gnfpL3RM