vb.net DataGrid Windows 控件执行分页

http://support.microsoft.com/kb/305271/zh-cn



DataGrid Web 控件有内置的自动或自定义分页功能,但是 DataGrid Windows 控件却没有这些功能。本文介绍如何为 DataGrid Windows 控件生成简单的分页机制。

本文中的代码示例利用了数据集对象。在 ADO.NET 中,数据集对象是通过单次操作填充的,它们始终驻留在内存中。如果您在使用一个大型数据集,本文介绍如何以编程方式按块区或页面形式显示数据。

此技巧有一些局限性。有关更多信息,请参阅疑难解答一节。 

要求

  • Microsoft Visual Basic .NET
  • Microsoft SQL Server Northwind 示例数据库

向 DataGrid Windows 控件添加分页的步骤

当您对  DataGrid 进行分页时,您会在页面大小的"块区"中显示数据,也即,一次显示一页记录。下面的代码示例将每页的  DataRow 对象从内存中的 数据集复制到一个临时表中。该临时表然后会绑定到  DataGrid 控件。
  1. 打开一个新的 Visual Basic .NET Windows 应用程序。默认情况下将创建 Form1。
  2. 添加 DataGrid 控件,将其 ReadOnly 属性设置为 True
  3. 将以下附加控件添加到 Form1 上,然后按如下所示设置它们的属性:
    Control Name Property Text Property
    Button btnFirstPage First Page
    Button btnNextPage Next Page
    TextBox txtDisplayPageNo  
    Button btnPreviousPage Previous Page
    Button btnLastPage Last Page
    TextBox txtPageSize 5
    Button btnFillGrid Fill Grid

  4. 复制下面的代码并粘贴到 Form1 的 General Declaration 部分:
    Imports System
    Imports System.Data
    Imports System.Data.SqlClient
  5. 复制下面的代码并粘贴到"Windows Form Designer generated code"区域之前 以声明 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. 删除 Form1 的 Load 事件自动生成的下列代码。
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles MyBase.Load
    
    End Sub
  7. 复制下面的代码并粘贴到"Windows Form Designer generated code"区域之后
    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. 修改代码中的 ConnectionString 参数以使它指向罗斯文 (Northwind) 数据库的一个现有实例。
  9. 按 F5 键生成并运行此项目。
  10. 默认情况下,将"页大小"设置为 5 个记录,您可以在文本框中更改它。
  11. 单击填充网格。注意,网格中填入了 5 个记录。
  12. 单击第一页下一页上一页 和最后一页可以在不同的页面之间浏览。


VB DataGrid分页 请看: 数据库:test2000.mdb 表:numbers 字段:Id(自动编号),anumber(数字) 因为DataGrid控件我们采用直接绑定记录集来显示数据.所以分页处理我们采用了间接的办法,定义另一个记录集objrs,将分页后的记录集付给objrs.然后绑定DataGrid ''效果还不错 , 我加了详细地注释,像pagesize, AbsolutePage的用法可参考msdn VB中新建工程,form中添加DataGrid控件,按钮cmdPrevious和cmdNext,文本框txtPage ''引用microsoft active data object 2.x object library Option Explicit Dim conn As ADODB.Connection Dim lCurrentPage As Long Private Sub cmdNext_Click() lCurrentPage = lCurrentPage + 1 Call Loadcontrol(lCurrentPage) End Sub Private Sub cmdPrevious_Click() If lCurrentPage > 1 Then lCurrentPage = lCurrentPage - 1 Call Loadcontrol(lCurrentPage) End If End Sub Private Sub Form_Load() Set conn = New ADODB.Connection conn.CursorLocation = adUseClient conn.Open "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\test2000.mdb;" lCurrentPage = 1 Call Loadcontrol(lCurrentPage) End Sub Private Sub Loadcontrol(lPage As Long) Dim adoPrimaryRS As ADODB.Recordset Dim lPageCount As Long Dim nPageSize As Integer Dim lCount As Long ''每页显示的纪录 nPageSize = 10 Set adoPrimaryRS = New ADODB.Recordset adoPrimaryRS.Open "select * from numbers", conn, adOpenStatic, adLockOptimistic adoPrimaryRS.PageSize = nPageSize ''页数 lPageCount = adoPrimaryRS.PageCount If lCurrentPage > lPageCount Then lCurrentPage = lPageCount End If adoPrimaryRS.AbsolutePage = lCurrentPage ''定义另一个记录集 Dim objrs As New ADODB.Recordset ''添加字段名称 For lCount = 0 To adoPrimaryRS.Fields.Count - 1 objrs.Fields.Append adoPrimaryRS.Fields(lCount).Name, adVarChar, adoPrimaryRS.Fields(lCount).DefinedSize Next ''打开记录集 objrs.Open ''将指定记录数循环添加到objrs中 For lCount = 1 To nPageSize objrs.AddNew objrs!id = adoPrimaryRS!id objrs!anumber = adoPrimaryRS!anumber adoPrimaryRS.MoveNext Next ''绑定 Set DataGrid1.DataSource = objrs ''在文本框显示页数 txtPage = lPage & "/" & adoPrimaryRS.PageCount End Sub Private Sub Form_Unload(Cancel As Integer) If Not conn Is Nothing Then conn.Close End If Set conn = Nothing End Sub ‘文本框中输入页数,回车跳转到指定位置 Private Sub txtPage_KeyDown(KeyCode As Integer, Shift As Integer) lCurrentPage = Val(txtPage.Text) Call Loadcontrol(lCurrentPage) End Sub
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值