百寶箱為你解決ADO.NET分頁煩惱
ADO.NET分頁還是比較常用的,于是我研究了一下ADO.NET分頁,在這里拿出來和大家分享一下,希望對大家有用。查詢結(jié)果ADO.NET分頁是以較小數(shù)據(jù)子集(即頁)的形式返回查詢結(jié)果的過程。 它通常用于以易于管理的小塊形式向用戶顯示結(jié)果。
#T#DataAdapter 提供了通過 Fill 方法的重載來僅返回一頁數(shù)據(jù)的功能。 但是,對于大量的查詢結(jié)果,它可能并不是首選的分頁方法,因?yàn)?DataAdapter 雖然僅使用所請求的記錄來填充目標(biāo) DataTable 或 DataSet,但仍會使用返回整個查詢的資源。 若要在從數(shù)據(jù)源中返回一頁數(shù)據(jù)時不使用返回整個查詢的資源,請為查詢指定附加條件,使返回的行數(shù)減少到只返回所需的行。若要使用 Fill 方法返回一頁數(shù)據(jù),請指定 startRecord 參數(shù)(代表該數(shù)據(jù)頁中的第一個記錄),并指定 maxRecords 參數(shù)(代表該數(shù)據(jù)頁中的記錄數(shù))。
以下代碼示例顯示如何使用 Fill 方法來返回查詢結(jié)果(頁大小為 5 個記錄)的第一頁。
Visual Basic
- Dim currentIndex As Integer = 0
- Dim pageSize As Integer = 5
- Dim orderSQL As String = "SELECT * FROM dbo.Orders ORDER BY OrderID"
- ' Assumes that connection is a valid SqlConnection object.
- Dim adapter As SqlDataAdapter = _
- New SqlDataAdapter(orderSQL, connection)
- Dim dataSet As DataSet = New DataSet()
- adapter.Fill(dataSet, currentIndex, pageSize, "Orders")
C#
- int currentIndex = 0;
- int pageSize = 5;
- string orderSQL = "SELECT * FROM Orders ORDER BY OrderID";
- // Assumes that connection is a valid SqlConnection object.
- SqlDataAdapter adapter = new SqlDataAdapter(orderSQL, connection);
- DataSet dataSet = new DataSet();
- adapter.Fill(dataSet, currentIndex, pageSize, "Orders");