News Ticker

Menu

Paging trong Repeater Asp.net

(Paging in Repeater in asp.net) – Kỹ thuật phân trang là quá trình hiển thị số lượng lớn các bản ghi bằng cách phân nhỏ dữ liệu vào các trang khác nhau giúp cho ứng dụng của tải dữ liệu nhanh và thao tác nhanh hơn. Nếu việc hiển thị dữ liệu sử dụng Control Gridview thì việc này đơn giản vì chức năng này đã được hỗ trợ. Nhưng khi sử dụng Control Repeater thì chức năng AllowPaging không được hỗ trợ. Vậy có cách nào để tự bổ xung thêm chức năng phân trang cho Repeater không? Bài viết dưới đây sẽ hướng dẫn các bạn thêm Control Paging cho Repeater.


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 tại đây và thực hiện công việc Restore Data.

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

C# Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace PagingRepeater
{
    public class SqlDataProvider
    {
        #region "Membres Prives"

        private string _connectionString;

        #endregion

        #region "Constructeurs"

        public SqlDataProvider()
        {
            try
            {
                _connectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
            }
            catch
            {
            }
        }

        #endregion

        #region "Proprietes"

        public string ConnectionString
        {
            get { return _connectionString; }
        }

        #endregion

        #region "Functions"

        public DataSet FillTable(string sql)
        {
            try
            {
                DataSet tb = new DataSet();
                SqlDataAdapter adap = new SqlDataAdapter(sql, _connectionString);
                adap.Fill(tb);
                return tb;
            }
            catch
            {
                return null;
            }
        }

        #endregion
    }
}
VB.NET Code
Imports System.Data.SqlClient
Imports System.Data

Namespace PagingRepeater

    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 DataSet
            Try
                Dim tb As New DataSet
                Dim adap As New SqlDataAdapter(sql, _connectionString)
                adap.Fill(tb)
                Return tb
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

#End Region

    End Class

End Namespace

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

B3: Mở file Site.css bổ xung thêm đoạn mã dưới
.paging_active
{
    display: inline-block;
    height: 25px;
    min-width: 25px;
    line-height: 25px;
    text-align: center;
    text-decoration: none;
    border: 1px solid #337AB7;
    margin:1px;
    background-color: #337AB7;
    color: #FFF !important;
}
       
.paging
{
    display: inline-block;
    height: 25px;
    min-width: 25px;
    line-height: 25px;
    text-align: center;
    text-decoration: none;
    border: 1px solid #ccc;
    margin:1px;
    background-color: #eee;
    color: #000;
}

.captions
{
    font-family: Tahoma;
    font-size: 9pt;
    font-weight: bold;
    color: #000000;
    background-color: #f5f5f5;
    height: 28px;
}

.RowStyle
{
    background-color: #ffffff;
}

.AlternatingRowStyle
{
    background-color: #edf5ff;
}

B4: Mở file Default.aspx dưới dạng HTML và  nhập mã HTML
C# Code
<%@ Page Title="Paging Repeater in ASP.NET" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PagingDatalist._Default" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" EnablePageMethods = "true" runat="server">
    </asp:ScriptManager>
    <h2>
        Paging Repeater in ASP.NET
    </h2>
    <br />
    <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table cellpadding="0" cellspacing="0" width="100%" >
                <tr id="trMessage" runat="server" visible="false">
                    <td>
                        <asp:Label ID="lblMessage" runat="server"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Repeater ID="dlObject" runat="server">
                            <HeaderTemplate>
                            <table cellpadding="4" cellspacing="5" width="100%" style="BORDER-COLLAPSE: collapse" borderColor="#cccccc" border="1">
                                <tr class="captions">
                                    <th align="center" width="220">ProductName</th>
                                    <th align="center" width="180">CategoryName</th>
                                    <th align="center" width="100">QuantityPerUnit</th>
                                    <th align="center" width="80">UnitPrice</th>
                                    <th align="center" width="80">UnitsInStock</th>
                                    <th align="center" width="80">UnitsOnOrder</th>                             
                                </tr>
                            </HeaderTemplate>
                            <ItemTemplate>
                                <tr class="<%#(Container.ItemIndex+1)%2==0?"AlternatingRowStyle":"RowStyle"%>">
                                    <td align="left" width="220"><%# Eval("ProductName") %></td>
                                    <td align="left" width="180"><%# Eval("CategoryName") %></td>
                                    <td align="left" width="100"><%# Eval("QuantityPerUnit") %></td>
                                    <td align="right" width="80"><%# Eval("UnitPrice") %></td>
                                    <td align="right" width="80"><%# Eval("UnitsInStock") %></td>
                                    <td align="right" width="80"><%# Eval("UnitsOnOrder") %></td>       
                                </tr>
                            </ItemTemplate>
                            <FooterTemplate>
                            </table>
                            </FooterTemplate>
                        </asp:Repeater>
                    </td>
                </tr>
                <tr>
                    <td style="padding-top:15px;">
                        <asp:Panel ID="pnlPaging" Runat="server" visible="false">
                               <asp:HyperLink ID="lnkPrev" Runat="server" CssClass="CommandButton"><span class="paging"><<</span></asp:HyperLink>
                               <asp:label id="lblCurrentPage" runat="server"></asp:label>
                               <asp:HyperLink ID="lnkNext" Runat="server" CssClass="CommandButton"><span class="paging">>></span></asp:HyperLink>
                        </asp:Panel>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

VB.NET Code
<%@ Page Title="DropDownList AutoComplete and Filtering in ASP.Net" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AutoCompleteandFilteringDropdownlist._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <h3>
      DropDownList AutoComplete and Filtering in ASP.Net
    </h3>
    <br />
    <script type="text/jscript">
        function pageLoad() {
            $("#" + "<%=ddlObject.ClientID%>").select2();
        };
    </script>
    <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table cellpadding="0" cellspacing="0" width="60%">
                <tr>
                    <td>
                        <asp:DropDownList ID="ddlObject" runat="server" Width="250px">
                        </asp:DropDownList>
                        <asp:LinkButton id="cmdSubmit" runat="server" OnClick="cmdSubmit_Click" Text="Submit" Causesvalidation="true">
                        </asp:LinkButton>
                    </td>
                </tr>
                <tr>
                    <td>
                        <br /><asp:Label ID="lblMessage" runat="server"></asp:Label>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

B5: 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 PagingDatalist
{
    public partial class _Default : System.Web.UI.Page
    {

        #region "Bind Data"

        private void BindProduct()
        {
            DataSet objBind = new DataSet();
            objBind = BindData();

            if (objBind != null)
            {
                PagedDataSource pgd = new PagedDataSource();

                pgd.AllowPaging = true;
                pgd.DataSource = objBind.Tables[0].DefaultView;
                pgd.PageSize = 15;

                if (!string.IsNullOrEmpty(Request["Page"]))
                {
                    {
                        pgd.CurrentPageIndex = Convert.ToInt32(Request["Page"]);
                    }
                }

                if (pgd.PageCount > 1)
                {
                    pnlPaging.Visible = true;
                    lnkNext.Enabled = !pgd.IsLastPage;
                    if (lnkNext.Enabled)
                    {
                        lnkNext.NavigateUrl = "Default.aspx?Page=" + (pgd.CurrentPageIndex + 1).ToString();
                    }

                    lnkPrev.Enabled = !pgd.IsFirstPage;
                    if (lnkPrev.Enabled)
                    {
                        lnkPrev.NavigateUrl = "Default.aspx?Page=" + (pgd.CurrentPageIndex - 1).ToString();
                    }

                    string strPages = "";
                    for (int i = 1; i <= pgd.PageCount; i++)
                    {
                        if (i == (pgd.CurrentPageIndex + 1))
                        {
                            strPages = strPages + "<span class=\"paging_active\">" + i.ToString() + "</span>";
                        }
                        else
                        {
                            strPages = strPages + "<a href=Default.aspx?Page=" + (i - 1).ToString() + "><span class=\"paging\">" + i.ToString() + "</span></a>";
                        }
                    }
                    lblCurrentPage.Text = strPages;
                }
                else
                {
                    pnlPaging.Visible = false;
                }

                if (pgd != null)
                {
                    if (pgd.Count > 0)
                    {
                        dlObject.DataSource = pgd;
                        dlObject.DataBind();
                        trMessage.Visible = false;
                        dlObject.Visible = true;
                    }
                    else
                    {
                        trMessage.Visible = true;
                        dlObject.Visible = false;
                        lblMessage.Text = "No Data";
                    }
                    updatePanel.Update();
                }
            }
        }

        private DataSet BindData()
        {
            SqlDataProvider objSQL = new SqlDataProvider();
            DataSet objBind = objSQL.FillTable("SELECT Products.ProductID, Products.ProductName, Products.SupplierID, Products.CategoryID, Categories.CategoryName, Products.QuantityPerUnit, Products.UnitPrice, Products.UnitsInStock, Products.UnitsOnOrder, Products.ReorderLevel, Products.Discontinued From Products INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID");
            return objBind;
        }

        #endregion

        #region "Event Handles"

        protected void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    BindProduct();
                }
            }
            catch
            {
            }
        }

        #endregion
    }
}

VB.NET Code
'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
Imports System.Data

Namespace PaginginRepeater

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Bind Data"

        Private Sub BindProduct()
            Dim objBind As New DataSet
            objBind = BindData()

            If Not objBind Is Nothing Then
                Dim pgd As New PagedDataSource

                pgd.AllowPaging = True
                pgd.DataSource = objBind.Tables(0).DefaultView
                pgd.PageSize = 16

                If Request("Page") <> "" Then
                    Try
                        pgd.CurrentPageIndex = Convert.ToInt32(Request("Page"))
                    Catch ex As Exception
                        pgd.CurrentPageIndex = 1
                    End Try
                End If

                If pgd.PageCount > 1 Then
                    pnlPaging.Visible = True
                    lnkNext.Enabled = Not pgd.IsLastPage
                    If lnkNext.Enabled Then
                        lnkNext.NavigateUrl = "Default.aspx?Page=" & (pgd.CurrentPageIndex + 1).ToString()
                    End If

                    lnkPrev.Enabled = Not pgd.IsFirstPage
                    If lnkPrev.Enabled Then
                        lnkPrev.NavigateUrl = "Default.aspx?Page=" & (pgd.CurrentPageIndex - 1).ToString()
                    End If

                    Dim strPages As String = ""
                    For i As Integer = 1 To pgd.PageCount
                        If i = (pgd.CurrentPageIndex + 1) Then
                            strPages = strPages + "<span class=""paging_active"">" & i.ToString() & "</span>"
                        Else
                            strPages = strPages + "<a href=Default.aspx?Page=" & (i - 1).ToString() & "><span class=""paging"">" & i.ToString() & "</span></a>"
                        End If
                    Next
                    lblCurrentPage.Text = strPages
                Else
                    pnlPaging.Visible = False
                End If

                If Not pgd Is Nothing Then
                    If pgd.Count > 0 Then
                        dlObject.DataSource = pgd
                        dlObject.DataBind()
                        trMessage.Visible = False
                        dlObject.Visible = True
                    Else
                        trMessage.Visible = True
                        dlObject.Visible = False
                        lblMessage.Text = "No Data"
                    End If
                    updatePanel.Update()
                End If
            End If
        End Sub

        Private Function BindData() As DataSet
            Dim objSQL As New SqlDataProvider
            Dim objBind As DataSet = objSQL.FillTable("SELECT Products.ProductID, Products.ProductName, Products.SupplierID, Products.CategoryID, Categories.CategoryName, " & _
                                                      "Products.QuantityPerUnit, Products.UnitPrice, Products.UnitsInStock, Products.UnitsOnOrder, Products.ReorderLevel, " & _
                                                      "Products.Discontinued From Products INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID")
            Return objBind
        End Function

#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
                    BindProduct()
                End If
            Catch ex As Exception

            End Try
        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:

Post Tags:

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 " Paging trong Repeater 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