Help and Support

Id. de artículo: 305271 - Última revisión: domingo, 13 de mayo de 2007 - Versión: 4.1

Cómo realizar la paginación con el control DataGrid de Windows mediante Visual Basic .NET

Este artículo se publicó anteriormente con el número E305271

En esta página

Expandir todo | Contraer todo

Resumen

El control Web DataGrid tiene las funcionalidades de paginación automática o personalizada; sin embargo, el control de WindowsDataGrid carece de estas características. En este artículo se demuestra cómo crear un mecanismo de paginación simple para el control de Windows DataGrid.

En los ejemplos de código de este artículo se usan objetos DataSet. En ADO.NET, los objetos DataSet se rellenan en una única operación y residen en memoria todo el tiempo. Si está trabajando con un DataSet grande, este artículo describe cómo mostrar los datos en fragmentos o páginas mediante programación.

Esta técnica tiene algunas limitaciones. Consulte la sección Solución de problemas para obtener más información.

Requisitos

  • Microsoft Visual Basic .NET
  • Base de datos de ejemplo Northwind de Microsoft SQL Server

Pasos para agregar paginación a un control de Windows DataGrid

Cuando pagina un DataGrid, muestra los datos en "fragmentos" del tamaño de una página, es decir, una página de registros cada vez. El código de ejemplo copia los objetos DataRow para cada página del DataSet en memoria a una tabla temporal. La tabla temporal se enlaza a continuación al control DataGrid.
  1. Abra una nueva aplicación Windows en Visual Basic .NET. De forma predeterminada, se crea Form1.
  2. Agregue el control DataGrid y establezca su propiedad ReadOnly en True.
  3. Coloque los controles adicionales siguientes en Form1 y establezca sus propiedades como se muestra a continuación:
    Contraer esta tablaAmpliar esta tabla
    ControlNombre de propiedadTexto de la propiedad
    ButtonbtnFirstPagePrimera página
    ButtonbtnNextPagePágina siguiente
    TextBoxtxtDisplayPageNo
    ButtonbtnPreviousPagePágina anterior
    ButtonbtnLastPageÚltima página
    TextBoxtxtPageSize5
    ButtonbtnFillGridLlenar cuadrícula

  4. Copie y pegue el código siguiente en la sección de declaraciones generales de Form1:
    Imports System
    Imports System.Data
    Imports System.Data.SqlClient
    					
  5. Copie y pegue el código siguiente antes de la sección "Código generado por el Diseñador de Windows Forms" para declarar las variables de formulario para Form1:
        Private da As SqlDataAdapter
        Private ds As DataSet
        Private dtSource As DataTable
        Private PageCount As Integer
        Private maxRec As Integer
        Private pageSize As Integer
        Private currentPage As Integer
        Private recNo As Integer
    					
  6. Elimine el siguiente código generado automáticamente para el evento Load de Form1.
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
      Handles MyBase.Load
    
    End Sub
    					
  7. Copie y pegue el código siguiente después de la sección "Código generado por el Diseñador de Windows Forms":
    Private Sub Form1_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load
    
        'Open Connection.
        Dim conn As SqlConnection = New SqlConnection( _ 
    "Server=(local)\netsdk;uid=sa;pwd=;database=northwind")
    
        'Set the DataAdapter's query.
        da = New SqlDataAdapter("select * from customers", conn)
        ds = New DataSet()
    
        ' Fill the DataSet.
        da.Fill(ds, "customers")
    
        ' Set the source table.
        dtSource = ds.Tables("customers")
    
    End Sub
    
    Private Sub btnNextPage_Click(ByVal sender As System.Object, _ 
        ByVal e As System.EventArgs) Handles btnNextPage.Click
    
        'If the user did not click the "Fill Grid" button then Return
        If Not CheckFillButton() Then Return
    
        'Check if the user clicked the "Fill Grid" button.
        If pageSize = 0 Then
            MessageBox.Show("Set the Page Size, and then click the ""Fill Grid"" button!")
            Return
        End If
    
        currentPage = currentPage + 1
    
        If currentPage > PageCount Then
            currentPage = PageCount
    
            'Check if you are already at the last page.
            If recNo = maxRec Then
                MessageBox.Show("You are at the Last Page!")
                Return
            End If
        End If
    
        LoadPage()
    End Sub
    
    Private Sub btnPreviousPage_Click(ByVal sender As System.Object, _ 
        ByVal e As System.EventArgs) Handles btnPreviousPage.Click
    
        If Not CheckFillButton() Then Return
    
        If currentPage = PageCount Then
            recNo = pageSize * (currentPage - 2)
        End If
    
        currentPage = currentPage - 1
    
        'Check if you are already at the first page.
        If currentPage < 1 Then
            MessageBox.Show("You are at the First Page!")
            currentPage = 1
            Return
        Else
            recNo = pageSize * (currentPage - 1)
        End If
    
        LoadPage()
    End Sub
    
    Private Sub LoadPage()
        Dim i As Integer
        Dim startRec As Integer
        Dim endRec As Integer
        Dim dtTemp As DataTable
        Dim dr As DataRow
    
        'Duplicate or clone the source table to create the temporary table.
        dtTemp = dtSource.Clone
    
        If currentPage = PageCount Then
            endRec = maxRec
        Else
            endRec = pageSize * currentPage
        End If
    
        startRec = recNo
    
        'Copy the rows from the source table to fill the temporary table.
        For i = startRec To endRec - 1
            dtTemp.ImportRow(dtSource.Rows(i))
            recNo = recNo + 1
        Next
    
        DataGrid1.DataSource = dtTemp
        DisplayPageInfo()
    
    End Sub
    
    Private Sub btnFirstPage_Click(ByVal sender As System.Object, _ 
        ByVal e As System.EventArgs) Handles btnFirstPage.Click
    
        If Not CheckFillButton() Then Return
    
        ' Check if you are already at the first page.
        If currentPage = 1 Then
            MessageBox.Show("You are at the First Page!")
            Return
        End If
    
        currentPage = 1
        recNo = 0
    
        LoadPage()
    
    End Sub
    
    Private Sub btnLastPage_Click(ByVal sender As System.Object, _ 
        ByVal e As System.EventArgs) Handles btnLastPage.Click
    
        If Not CheckFillButton() Then Return
    
        ' Check if you are already at the last page.
        If recNo = maxRec Then
            MessageBox.Show("You are at the Last Page!")
            Return
        End If
    
        currentPage = PageCount
    
        recNo = pageSize * (currentPage - 1)
    
        LoadPage()
    
    End Sub
    
    Private Sub DisplayPageInfo()
        txtDisplayPageNo.Text = "Page " & currentPage.ToString & "/ " & PageCount.ToString
    End Sub
    
    Private Sub btnFillGrid_Click(ByVal sender As System.Object, _ 
        ByVal e As System.EventArgs) Handles btnFillGrid.Click
    
        'Set the start and max records. 
        pageSize = txtPageSize.Text
        maxRec = dtSource.Rows.Count
        PageCount = maxRec \ pageSize
    
        ' Adjust the page number if the last page contains a partial page.
        If (maxRec Mod pageSize) > 0 Then
            PageCount = PageCount + 1
        End If
    
        'Initial seeings
        currentPage = 1
        recNo = 0
    
        ' Display the content of the current page.
        LoadPage()
    
    End Sub
    
    Private Function CheckFillButton() As Boolean
    
        'Check if the user clicks the "Fill Grid" button.
        If pageSize = 0 Then
            MessageBox.Show("Set the Page Size, and then click the ""Fill Grid"" button!")
            CheckFillButton = False
        Else
            CheckFillButton = True
        End If
    End Function
    					
  8. Modifique el parámetro ConnectionString en el código para que señale a una instancia existente de la base de datos Northwind.
  9. Presione la tecla F5 para generar y ejecutar el proyecto.
  10. De forma predeterminada, el tamaño de página se establece en 5 registros, por lo que puede cambiarlo en el cuadro de texto.
  11. Haga clic en Rellenar cuadrícula. Observe que la cuadrícula se llena con 5 registros.
  12. Haga clic en Primera página, Página siguiente, Página anteriory Última página para desplazarse entre las páginas.

Solución de problemas

  • Esta técnica sólo funciona con los controles DataGrid de sólo lectura. Cuando importa una fila en un objeto DataTable temporal, realiza una copia. Por lo tanto, los cambios que haga no se guardarán en la tabla principal.
  • Esta técnica no funciona (ni tampoco una colección o una matriz) si desea que el usuario pueda desplazarse a los registros secundarios a través de un objeto DataRelation o si tiene registros que están vinculados en una relación primario-secundario que aparece al mismo tiempo en el formulario.

Referencias

Para obtener más información acerca de ADO.NET, visite el sitio Web de MSDN siguiente:
Accessing Data with ADO.NET
http://msdn2.microsoft.com/en-us/library/e80y5yhx(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/e80y5yhx(vs.71).aspx)
Para obtener más información, consulte la documentación del SDK de Microsoft .NET Framework:
SDK de .NET Framework
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/netstart/html/sdk_netstart.asp (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/netstart/html/sdk_netstart.asp)

La información de este artículo se refiere a:
  • Microsoft ADO.NET 1.0
  • Microsoft ADO.NET 1.1
  • Microsoft Visual Basic .NET 2003 Standard Edition
  • Microsoft Visual Basic .NET 2002 Standard Edition
Palabras clave: 
kbdatabinding kbhowtomaster kbwindowsforms KB305271

Seleccione idioma