嗨,我有一个包含 100000 行数据的表。现在我想以页面大小为 50 的用户表单显示我的数据。
呈现它的最佳方法是什么。我更喜欢数据列表吗?或者我可以实现我自己的选择查询,每次按下下一个按钮时获取 50 条记录?
提前致谢
如果你打开 GridViewAllowPaging
并将其设置PageSize
为 50 ,你可以很容易地做到这一点。但这会非常低效 - 每次你移动到一个新页面时,它都会读取所有 1 000 000 行,计算出它需要哪 50 行展示,其余的扔掉。
相反,您需要的是数据库中的存储过程,它获取您要显示的页码,计算出该页面上的行集并将它们返回到 ASP.NET 页面。如果您使用的是 SQL Server 2005 或更高版本,最好的选择是使用公用表表达式,因此您的存储过程将如下所示(这是用于 Northwind db):
CREATE PROC [dbo].[PagedOrderList]
@PageNumber INTEGER
AS
SET NOCOUNT ON
DECLARE @lowerRecordNumber INTEGER
DECLARE @upperRecordNumber INTEGER
-- Work out the record numbers that bound the page
SET @lowerRecordNumber = ((@pageNumber - 1) * 50) + 1
SET @upperRecordNumber = (@pageNumber * 50);
-- Create a CTE with all the records numbered
WITH OrdersCTE ([RowNumber],[OrderId],[OrderDate],[RequiredDate],[ShippedDate],
[CompanyName],[Value])
AS
(
SELECT
ROW_NUMBER() OVER(ORDER BY o.[OrderId]),
o.OrderID,
o.OrderDate,
o.RequiredDate,
o.ShippedDate,
c.CompanyName,
SUM(od.Quantity * od.UnitPrice) AS [Value]
FROM
Orders o INNER JOIN [Order Details] od ON o.OrderID = od.OrderID
INNER JOIN Customers c ON o.CustomerID = c.CustomerID
GROUP BY o.OrderID, o.OrderDate, o.RequiredDate, o.ShippedDate, c.CompanyName
)
-- Select the rows from the CTE that fall between the bounds we worked out
SELECT *
FROM OrdersCTE
WHERE [RowNumber] BETWEEN @lowerRecordNumber AND @upperRecordNumber
现在,回到你的页面。您需要放入一个 DataGrid——它们比其他任何东西都更好地支持自定义分页——并设置AllowCustomPaging
为 True。您可能会发现使用一种使用页码调用存储过程的方法更容易,然后您可以添加上一个、下一个、第一个、最后一个、+10、-10 按钮 - 无论您想要什么,只需计算出页码并通过它的方法。
Private Sub loadData(ByVal pageNumber As Integer)
Dim orderDataTable As DataTable
'This uses the Microsoft Enterprise Library for data access
Dim DAL As Database
Dim cmd As DbCommand
DAL = DatabaseFactory.CreateDatabase("Northwind")
cmd = DAL.GetStoredProcCommand("PagedOrderList")
'Pass the page number to the stored proc
DAL.AddInParameter(cmd, "@pageNumber", DbType.Int32, pageNumber)
'Get a DataTable back with the 50 rows we want
orderDataTable = DAL.ExecuteDataSet(cmd).Tables(0)
'Bind the data to the grid
With OrderDataGrid
.DataSource = orderDataTable
.DataBind()
'Set the page number so we know where we are in the dataset
.CurrentPageIndex = pageNumber
End With
End Sub
Private Sub PreviousButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles PreviousButton.Click
If OrderDataGrid.CurrentPageIndex = 0 Then
'Make sure we don't try to load a negative page number
Else
'Work out the previous page number and load the data for it
Call loadData(OrderDataGrid.CurrentPageIndex - 1)
End If
End Sub
Private Sub NextButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles NextButton.Click
'Work out the nextpage number and load the data for it
Call loadData(OrderDataGrid.CurrentPageIndex + 1)
End Sub
我为asp.net 创建了一个分页控件。这是一个基本的控制,但它可以帮助你。基本寻呼机控制
对于 100000,将所有记录从数据库中获取到数据集中然后分页将非常耗时。相反,我会在数据库存储过程/查询中实现分页。这样,一次只能在前端代码中检索 50 条记录,并且用户响应会更快。
“ListView”和“DataPager”呢?
我会使用 pagedDataSource 然后您可以绑定到中继器、数据列表或其他任何东西。
这里有例子。