是的,ASP.NET GridView 分页可以与存储过程结合使用。为了实现这一点,您需要执行以下步骤:
例如,假设您有一个名为 GetUsers
的存储过程,它接受两个参数:@PageIndex
(页码)和@PageSize
(每页显示的记录数)。存储过程可以根据这些参数查询用户数据并返回结果。
CREATE PROCEDURE GetUsers
@PageIndex INT,
@PageSize INT
AS
BEGIN
SELECT * FROM Users
ORDER BY UserID
OFFSET (@PageIndex - 1) * @PageSize ROWS
FETCH NEXT @PageSize ROWS ONLY;
END
using System.Data;
using System.Data.SqlClient;
public DataTable GetPagedUsers(int pageIndex, int pageSize)
{
string connectionString = "your_connection_string";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("GetUsers", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@PageIndex", pageIndex);
command.Parameters.AddWithValue("@PageSize", pageSize);
using (SqlDataReader reader = command.ExecuteReader())
{
DataTable result = new DataTable();
result.Load(reader);
return result;
}
}
}
}
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="10" OnPageIndexChanging="GridView1_PageIndexChanging">
</asp:GridView>
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
int pageIndex = e.NewPageIndex;
int pageSize = GridView1.PageSize;
DataTable pagedUsers = GetPagedUsers(pageIndex, pageSize);
GridView1.DataSource = pagedUsers;
GridView1.DataBind();
}
这样,当用户更改 GridView 的页码时,GridView1_PageIndexChanging
事件处理程序将被调用,从而调用存储过程并获取相应的分页数据。