Paginación perfecta con Repeater Control en ASP.net C#

A diferencia del GridView Crontol en ASP.net, el Repeater Control no admite la función de paginación al mostrar largas listas de datos en tu página web. Entonces, si quieres mostrar muchos datos en una página, ¿qué hay que hacer? En vez de utilizar el Repeater Control, ¿estamos obligados a utilizar el GridView Control? Mucha gente habrá llegado a la misma conclusión.

Sin embargo, si sólo queremos mostrar los datos en una página web como si fuese una tabla, entonces utilizar el GridView es una muy buena opción. Pero, si deseamos listar los datos en una página web sin ningún estilo predefinido, entonces no podrás. Conclusión, tenemos que usar el control Repeater como un reemplazo para el GridView.

En este artículo vamos a utilizar el Visual Studio Enterprise 2015, .NET Framework 4.5.2, ADO.Net, Asp.Net C# y el Repeater para enseñarte "Cómo implementar la función de paginación con el Repeater Control". Seguro que pensáis que tenemos una gran cantidad de las directivas actuales en Internet para la implementación de una función de paginado. Pero, personalmente creo que solo muestran un concepto básico limitando funciones y no encontré ninguno que satisfaciera.

Si sigues paso por paso este tutorial, al final deberás obtener una algo así:

Pasos para implementar la paginación

Paso 1. Antes que nada, creamos una tabla llamada tblPerson en la base de datos tal que así:

CREATE TABLE [dbo].[tblPerson](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [name] [nvarchar](50) NULL,
    [address] [nvarchar](50) NULL,
    [createdDate] [datetime] NULL,
 CONSTRAINT [PK_tblPerson] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

Paso 2. Inserta algunos datos de prueba en la tabla tblPerson que acabamos de crear.

Paso 3. Abre Visual Studio, y crea un nuevo proyecto web o una nueva página web.

Paso 4. Abre el Web.config para añadir el tag de Connectionstrings. Recuerda que debes entrar después en la base de datos para habilitar la conexión con el proyecto.

<connectionStrings>
    <add name="stringConnection" connectionString="Data Source = CHIENVH-PC;Initial Catalog=MyDB;Persist Security Info=True;User ID=sa; Password=123456789;"/>
  </connectionStrings>

Paso 5. Crea una página web con el nombre que sea, en este artículo la llamaremos Default.aspx. Copia el código de más abajo para llevar a cabo el front-end:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PerfectPaginationWithRepeater.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Perfect Pagination With Repeater and ASP.Net C#</title>
    <style type="text/css">
        .auto-style1 {
            width: 100%;
        }

        .auto-style3 {
            width: 162px;
        }

        table {
            border-collapse: collapse;
        }

        table, td, th {
            border: 1px solid blue;
        }

        th {
            background-color: dodgerblue;
            color: white;
        }
    style>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="MainScriptManager" runat="server" />
        <asp:UpdatePanel ID="pnlHelloWorld" runat="server">
            <ContentTemplate>
                <div>
                    <asp:Repeater ID="rptResult" runat="server">
                        <HeaderTemplate>
                            <table class="auto-style1">
                                <tr>
                                    <th>ID</th>
                                    <th>Name</th>
                                    <th>Address</th>
                                    <th>Created Date</th>
                                </tr>
                        </HeaderTemplate>
                        <ItemTemplate>
                            <tr>
                                <td><%#Eval("Id") %></td>
                                <td><%#Eval("Name") %></td>
                                <td><%#Eval("Address") %></td>
                                <td><%#Eval("createdDate") %></td>
                            </tr>
                        </ItemTemplate>
                        <FooterTemplate>
                            </table>
                        </FooterTemplate>
                    </asp:Repeater>
                </div>

                <div style="margin-top: 20px;">
                    <table style="width: 600px;">
                        <tr>
                            <td>
                                <asp:LinkButton ID="lbFirst" runat="server" OnClick="lbFirst_Click">First</asp:LinkButton>
                            </td>
                            <td>
                                <asp:LinkButton ID="lbPrevious" runat="server" OnClick="lbPrevious_Click">Previous</asp:LinkButton>
                            </td>
                            <td>
                                <asp:DataList ID="rptPaging" runat="server"
                                    OnItemCommand="rptPaging_ItemCommand"
                                    OnItemDataBound="rptPaging_ItemDataBound" RepeatDirection="Horizontal">
                                    <ItemTemplate>
                                        <asp:LinkButton ID="lbPaging" runat="server"
                                            CommandArgument='<%# Eval("PageIndex") %>' CommandName="newPage"
                                            Text='<%# Eval("PageText") %> ' Width="20px"></asp:LinkButton>
                                    </ItemTemplate>
                                </asp:DataList>
                            </td>
                            <td>
                                <asp:LinkButton ID="lbNext" runat="server" OnClick="lbNext_Click">Next</asp:LinkButton>
                            </td>
                            <td>
                                <asp:LinkButton ID="lbLast" runat="server" OnClick="lbLast_Click">Last</asp:LinkButton>
                            </td>
                            <td>
                                <asp:Label ID="lblpage" runat="server" Text=""></asp:Label>
                            </td>
                        </tr>
                    </table>

                </div>
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>

Paso 6. En el código de detrás, pega estas líneas:

 

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PerfectPaginationWithRepeater
{
    public partial class Default : System.Web.UI.Page
    {
        readonly PagedDataSource _pgsource = new PagedDataSource();
        int _firstIndex, _lastIndex;
        private int _pageSize = 10;
        private int CurrentPage
        {
            get
            {
                if (ViewState["CurrentPage"] == null)
                {
                    return 0;
                }
                return ((int)ViewState["CurrentPage"]);
            }
            set
            {
                ViewState["CurrentPage"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack) return;
            BindDataIntoRepeater();
        }

        // Get data from database/repository
        static DataTable GetDataFromDb()
        {
            var con = new SqlConnection(ConfigurationManager.ConnectionStrings["stringConnection"].ToString());
            con.Open();
            var da = new SqlDataAdapter("Select Id, Name, Address, CreatedDate From tblPerson Order By Id desc", con);
            var dt = new DataTable();
            da.Fill(dt);
            con.Close();
            return dt;
        }

        // Bind PagedDataSource into Repeater
        private void BindDataIntoRepeater()
        {
            var dt = GetDataFromDb();
            _pgsource.DataSource = dt.DefaultView;
            _pgsource.AllowPaging = true;
            // Number of items to be displayed in the Repeater
            _pgsource.PageSize = _pageSize;
            _pgsource.CurrentPageIndex = CurrentPage;
            // Keep the Total pages in View State
            ViewState["TotalPages"] = _pgsource.PageCount;
            // Example: "Page 1 of 10"
            lblpage.Text = "Page " + (CurrentPage + 1) + " of " + _pgsource.PageCount;
            // Enable First, Last, Previous, Next buttons
            lbPrevious.Enabled = !_pgsource.IsFirstPage;
            lbNext.Enabled = !_pgsource.IsLastPage;
            lbFirst.Enabled = !_pgsource.IsFirstPage;
            lbLast.Enabled = !_pgsource.IsLastPage;

            // Bind data into repeater
            rptResult.DataSource = _pgsource;
            rptResult.DataBind();

            // Call the function to do paging
            HandlePaging();
        }

        private void HandlePaging()
        {
            var dt = new DataTable();
            dt.Columns.Add("PageIndex"); //Start from 0
            dt.Columns.Add("PageText"); //Start from 1

            _firstIndex = CurrentPage - 5;
            if (CurrentPage > 5)
                _lastIndex = CurrentPage + 5;
            else
                _lastIndex = 10;

            // Check last page is greater than total page then reduced it to total no. of page is last index
            if (_lastIndex > Convert.ToInt32(ViewState["TotalPages"]))
            {
                _lastIndex = Convert.ToInt32(ViewState["TotalPages"]);
                _firstIndex = _lastIndex - 10;
            }

            if (_firstIndex < 0)
                _firstIndex = 0;

            // Now creating page number based on above first and last page index
            for (var i = _firstIndex; i < _lastIndex; i++)
            {
                var dr = dt.NewRow();
                dr[0] = i;
                dr[1] = i + 1;
                dt.Rows.Add(dr);
            }

            rptPaging.DataSource = dt;
            rptPaging.DataBind();
        }

        protected void lbFirst_Click(object sender, EventArgs e)
        {
            CurrentPage = 0;
            BindDataIntoRepeater();
        }
        protected void lbLast_Click(object sender, EventArgs e)
        {
            CurrentPage = (Convert.ToInt32(ViewState["TotalPages"]) - 1);
            BindDataIntoRepeater();
        }
        protected void lbPrevious_Click(object sender, EventArgs e)
        {
            CurrentPage -= 1;
            BindDataIntoRepeater();
        }
        protected void lbNext_Click(object sender, EventArgs e)
        {
            CurrentPage += 1;
            BindDataIntoRepeater();
        }

        protected void rptPaging_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (!e.CommandName.Equals("newPage")) return;
            CurrentPage = Convert.ToInt32(e.CommandArgument.ToString());
            BindDataIntoRepeater();
        }

        protected void rptPaging_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            var lnkPage = (LinkButton)e.Item.FindControl("lbPaging");
            if (lnkPage.CommandArgument != CurrentPage.ToString()) return;
            lnkPage.Enabled = false;
            lnkPage.BackColor = Color.FromName("#00FF00");
        }
    }
}

 

Paso 7. Ejecuta la aplicación para disfrutar de esta función. Si tenéis alguna pregunta al respecto, no dudéis en decírnoslo en los comentarios...

COMPARTE ESTE ARTÍCULO

COMPARTIR EN FACEBOOK
COMPARTIR EN TWITTER
COMPARTIR EN LINKEDIN
COMPARTIR EN WHATSAPP
ARTÍCULO ANTERIOR