asp.net 打印 分页 示例
时间: 2024-11-25 14:22:28 浏览: 22
ASP.NET 中打印分页功能通常用于展示大量数据列表,并通过页码让用户逐页浏览。下面是一个基本的例子,展示了如何使用`GridView`控件进行分页打印:
```csharp
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" AllowPaging="True" PageSize="10">
<Columns>
<!-- 添加列 -->
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:YourConnectionString %>"
SelectCommand="SELECT * FROM YourTable" />
<asp:Button ID="btnPrint" runat="server" Text="打印当前页" OnClick="btnPrint_Click" />
protected void btnPrint_Click(object sender, EventArgs e)
{
int currentPage = GridView1.PageIndex + 1; // 获取当前页码
// 创建一个新的HttpResponse对象,模拟打印机输出
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ContentType = "application/pdf";
response.AddHeader("Content-Disposition", "attachment; filename=page_" + currentPage + ".pdf");
// 设置页面范围,例如只打印当前页
GridView1.PageIndex = currentPage - 1;
string sql = "SELECT * FROM YourTable OFFSET " + (currentPage - 1) * GridView1.PageSize + " ROWS FETCH NEXT " + GridView1.PageSize + " ROWS ONLY"; // SQL查询以获取指定页的数据
GridView1.DataSource = SqlDataSource1.SelectCommand = sql;
GridView1.DataBind();
// 将GridView的内容发送到响应流
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
response.Write(sw.ToString());
// 清理并结束响应
response.Flush();
response.Close();
}
```
在这个示例中,用户点击“打印当前页”按钮时,会生成一个PDF文件,包含当前显示的那一页数据。
阅读全文