Controlo
DataGrid Web tem funcionalidades incorporadas automático ou personalizar páginas; no entanto, estas funcionalidades não possui o controlo
DataGrid do Windows. Este artigo demonstra como criar um mecanismo simples de paginação para o controlo
DataGrid Windows.
Os exemplos de código neste artigo fazem uso do
DataSet objectos. No ADO.NET,
DataSet objectos são preenchidos numa única operação em residem na memória sempre. Se estiver a trabalhar com um grande
DataSet , este artigo descreve como apresentar os dados em secções ou páginas programaticamente.
Esta técnica tem algumas limitações. Consulte a secção
Troubleshooting para obter mais informações.
Requisitos
- Microsoft Visual Basic .NET
- Dados de exemplo Adamastor do Microsoft SQL Server
Passos para adicionar um controlo DataGrid Windows paginação
Quando a página um
DataGrid Mostrar dados numa tamanho da página "blocos", ou seja, uma página de registos de cada vez. O código de exemplo a seguir copia os objectos de
DataRow para cada página o
DataSet na memória para uma tabela temporária. A tabela temporária, em seguida, está vinculada ao controlo
DataGrid .
- Abra um novo Visual Basic .NET Windows Application. É criado o Form1 por predefinição.
- Adicione o controlo DataGrid e defina a propriedade só de leitura para Verdadeiro .
- Coloque os seguintes controlos adicionais no Form1 e definir as respectivas propriedades conforme é ilustrado abaixo:
Reduzir esta tabelaExpandir esta tabela
| controlo | Propriedades de nome | Propriedades de texto |
|---|
| botão | btnFirstPage | Primeira página |
| botão | btnNextPage | Página seguinte |
| caixa de texto | txtDisplayPageNo | |
| botão | btnPreviousPage | Página anterior |
| botão | btnLastPage | Última página |
| caixa de texto | txtPageSize | 5 |
| botão | btnFillGrid | Preencher grelha |
- Copie e cole o código seguinte na secçã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 área de "Windows formulário Designer gerado código" declarar variáveis de nível do 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
- Eliminar o seguinte código gerado automaticamente para o evento carregar 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 depois da região "Criador de formulários Windows gerado 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
- Modificar o parâmetro ConnectionString no código de modo a que aponta para uma instância da base de dados Adamastor existente.
- Prima a tecla F5 para compilar e executar o projecto.
- Por predefinição, o tamanho da página está definido para 5 registos, para que possa alterar na caixa de texto.
- Clique em preenchimento grelha . Note que a grelha é preenchida com os 5 registos.
- Clique em Primeira página , Página seguinte , Página anterior e Última página para navegar entre páginas.
Resolução de problemas
- Esta técnica só funciona para controlos DataGrid só de leitura. Quando importa uma linha para um objecto DataTable temporário, efectue uma cópia. Assim, as alterações efectuadas não serão guardadas na tabela principal.
- Esta técnica não funciona (e não é uma colecção ou uma matriz) se pretender que o utilizador não conseguir navegar para registos através de um objecto DataRelation ou se tiver registos que estão ligados a uma relação de ascendente-subordinado que aparecem no formulário ao mesmo tempo.
Para mais informações sobre o ADO.NET, consulte a MSDN seguinte Web site:
Para mais informações, consulte o Microsoft .NET Framework SDK documentação: