明輝手游網(wǎng)中心:是一個免費提供流行視頻軟件教程、在線學(xué)習(xí)分享的學(xué)習(xí)平臺!

DataGrid也玩分頁

[摘要]呵呵,不是.NET的.這幾天論壇上回答問題,有人提出這個DataGrid控件的分頁。請看:?數(shù)據(jù)庫:test2000.mdb表:numbers字段:Id(自動編號),anumber(數(shù)字)?因為DataGrid控件我們采用直接綁定記錄集來顯示數(shù)據(jù).所以分頁處理我們采用了間接的辦法,定義另一個記錄集...
呵呵,不是.NET的.

這幾天論壇上回答問題,有人提出這個DataGrid控件的分頁。

請看:

?

數(shù)據(jù)庫:test2000.mdb

表:numbers

字段:Id(自動編號),anumber(數(shù)字)

?

因為DataGrid控件我們采用直接綁定記錄集來顯示數(shù)據(jù).所以分頁處理我們采用了間接的辦法,定義另一個記錄集objrs,將分頁后的記錄集付給objrs.然后綁定DataGrid

'效果還不錯 , 我加了詳細(xì)地注釋?像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

???

??? '每頁顯示的紀(jì)錄

??? nPageSize = 10

??? Set adoPrimaryRS = New ADODB.Recordset

??? adoPrimaryRS.Open "select * from numbers", conn, adOpenStatic, adLockOptimistic

?

??? adoPrimaryRS.PageSize = nPageSize

??? '頁數(shù)

??? 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

??? '將指定記錄數(shù)循環(huán)添加到objrs中

??? For lCount = 1 To nPageSize

??????? objrs.AddNew

??????? objrs!id = adoPrimaryRS!id

??????? objrs!anumber = adoPrimaryRS!anumber

??????? adoPrimaryRS.MoveNext

??? Next

??? '綁定

??? Set DataGrid1.DataSource = objrs

???

??? '在文本框顯示頁數(shù)

??? 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

‘文本框中輸入頁數(shù),回車跳轉(zhuǎn)到指定位置

Private Sub txtPage_KeyDown(KeyCode As Integer, Shift As Integer)

??? lCurrentPage = Val(txtPage.Text)

??? Call Loadcontrol(lCurrentPage)

End Sub




標(biāo)簽:DataGrid也玩分頁 

相關(guān)文章