O controle
DataGrid do Web tem funcionalidades automática ou personalizada paginação internas; no entanto, o controle
DataGrid do Windows não possui esses recursos. Este artigo demonstra como criar um simples mecanismo de paginação para o controle
DataGrid Windows.
Os exemplos de código neste artigo utilizam
DataSet objetos. No ADO.NET, objetos
DataSet são preenchidos em uma única operação e residem na memória o tempo todo. Se você estiver trabalhando com um grande
DataSet , este artigo descreve como exibir os dados em partes ou páginas programaticamente.
Essa técnica tem algumas limitações. Consulte a seção
Troubleshooting para obter mais informações.
Requisitos
- Microsoft Visual Basic .NET
- Banco de dados de exemplo Northwind do Microsoft SQL Server
Etapas para adicionar paginação a um controle DataGrid Windows
Quando a página um
DataGrid , você exibe dados em tamanho de página "blocos", ou seja, uma página de registros por vez. O código de exemplo a seguir copia os objetos
DataRow para cada página do
DataSet na memória para uma tabela temporária. A tabela temporária, em seguida, é vinculada ao controle
DataGrid .
- Abra um novo Visual Basic .NET Windows Application. O Form1 é criado por padrão.
- Adicione o controle DataGrid e defina sua propriedade ReadOnly como True .
- Posicione os seguintes controles adicionais no Form1 e defina suas propriedades conforme mostrado abaixo:
Recolher esta tabelaExpandir esta tabela
| controle | Propriedade Name | Propriedade de texto |
|---|
| botão | btnFirstPage | Primeira página |
| botão | btnNextPage | Próxima página |
| TextBox | txtDisplayPageNo | |
| botão | btnPreviousPage | Página anterior |
| botão | btnLastPage | Última página |
| TextBox | txtPageSize | 5 |
| botão | btnFillGrid | Preencher grade |
- Copie e cole o código a seguir em seção de declaração geral do Form1:
Imports System
Imports System.Data
Imports System.Data.SqlClient
- Copie e cole o seguinte código antes da região "Windows Form Designer gerou código" para declarar variáveis de nível de formulário 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
- Excluir o seguinte código gerado automaticamente para o evento Load do Form1.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles MyBase.Load
End Sub
- Copie e cole o seguinte código após a região "Windows Form Designer gerou código":
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
- Modifique o parâmetro ConnectionString o código para que ele aponta para uma instância existente do banco de dados Northwind.
- Pressione a tecla F5 para compilar e executar o projeto.
- Por padrão, o tamanho da página é definido como 5 registros, para que você possa alterá-lo na caixa de texto.
- Clique em preenchimento grade . Observe que a grade é preenchida com 5 registros.
- Clique em Primeira página , Avançar , Voltar e Última página para navegar entre páginas.
Solução de problemas
- Essa técnica funciona somente para controles DataGrid somente leitura. Quando você importa uma linha para um objeto DataTable temporário, faça uma cópia. Portanto, as alterações feitas não serão salvas para a tabela principal.
- Essa técnica não funciona (e não é uma coleção ou uma matriz) se desejar que o usuário navegue para registros filho através de um objeto DataRelation ou se você tiver registros que estão vinculados em uma relação pai-filho que aparecem no formulário ao mesmo tempo.
Para obter mais informações sobre como ADO.NET, consulte MSDN seguinte site:
Para obter mais informações, consulte o SDK do Microsoft .NET Framework documentação: