asp.net中datagridview分页代码
时间: 2024-05-03 20:17:57 浏览: 13
以下是ASP.NET中使用DataGridView进行分页的代码示例:
1.在页面上添加GridView控件和Pager控件:
```html
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Id" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" />
</Columns>
</asp:GridView>
<asp:Pager ID="Pager1" runat="server" />
```
2.在代码中获取数据并绑定到GridView:
```csharp
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
int pageSize = Pager1.PageSize; // 每页显示的记录数
int pageIndex = Pager1.CurrentPageIndex; // 当前页码
// 获取数据并进行分页
List<MyData> list = GetData();
int totalCount = list.Count;
int totalPages = (int)Math.Ceiling(totalCount / (double)pageSize);
int startIndex = (pageIndex - 1) * pageSize;
int endIndex = Math.Min(startIndex + pageSize, totalCount) - 1;
List<MyData> data = list.GetRange(startIndex, endIndex - startIndex + 1);
// 绑定数据到GridView
GridView1.DataSource = data;
GridView1.DataBind();
// 设置Pager控件的相关属性
Pager1.RecordCount = totalCount;
Pager1.TotalPages = totalPages;
}
```
3.在Pager控件的PageChanged事件中重新绑定GridView:
```csharp
protected void Pager1_PageChanged(object sender, EventArgs e)
{
BindGrid();
}
```
以上代码中的MyData是自定义的数据类,根据实际情况进行替换。另外,Pager控件需要在代码中设置PageSize和CurrentPageIndex属性的初始值,可以在Page_Load事件中进行设置。