在ASP.NET中,实现分页总数动态获取的方法如下:
public int GetRecordCount(int pageNumber)
{
// 计算偏移量
int offset = (pageNumber - 1) * pageSize;
// 查询数据库中的记录总数
int recordCount = 0;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT COUNT(*) FROM YourTable", connection))
{
recordCount = (int)command.ExecuteScalar();
}
}
return recordCount;
}
public DataTable GetPagedData(int pageNumber, int pageSize)
{
// 计算偏移量
int offset = (pageNumber - 1) * pageSize;
// 查询当前页的数据
DataTable dataTable = new DataTable();
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM YourTable ORDER BY YourColumn OFFSET @Offset ROWS FETCH NEXT @PageSize ROWS ONLY", connection))
{
command.Parameters.AddWithValue("@Offset", offset);
command.Parameters.AddWithValue("@PageSize", pageSize);
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
adapter.Fill(dataTable);
}
}
}
return dataTable;
}
GridView
),并为其设置AllowPaging
属性为true
。然后,为GridView
的PageIndexChanging
事件添加一个处理程序,以便在用户切换页面时调用上面创建的方法。<asp:GridView ID="GridView1" runat="server" AllowPaging="true" OnPageIndexChanging="GridView1_PageIndexChanging">
</asp:GridView>
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
// 获取当前页码和每页显示的记录数
int pageNumber = e.NewPageIndex + 1;
int pageSize = 10; // 你可以根据需要设置每页显示的记录数
// 获取当前页的数据
DataTable dataTable = GetPagedData(pageNumber, pageSize);
// 绑定数据到GridView
GridView1.DataSource = dataTable;
GridView1.DataBind();
}
现在,当用户在分页控件中切换页面时,ASP.NET将自动获取数据库中的记录总数,并根据用户选择的页码动态显示当前页的数据。