通过缓存Cache,来缓存Gridview里数据,在需要打印时就可以直接打印了。
打印界面:

缓存类:

Code
public class CacheData
{
private static CacheData instance;
private CacheData() { }
public static CacheData GetCache()
{
if (instance == null)
{
instance = new CacheData();
}
return instance;
}
public void CacheDataSet(DataTable dt) //设置要缓存的数据
{
HttpRuntime.Cache.Insert("printDT", dt, null, DateTime.Now.AddMinutes(20), TimeSpan.Zero);
}
public DataTable GetCacheData() //返回缓存的数据
{
if ((DataTable)HttpRuntime.Cache["printDT"] != null)
return (DataTable)HttpRuntime.Cache["printDT"];
else return null;
}
}
在数据绑定时就 CacheData.GetCache().CacheDataSet(dt); //缓存数据,用以打印
打印界面代码

Code
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Printer.aspx.cs" Inherits="DataManage_AppComFun_DeptManage_Printer" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>打印设置</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<!--media=print 这个属性可以在打印时有效-->
<style media=print type="text/css">
.Noprint{display:none;}
.PageNext{page-break-after: always;}
</style>
<style type="text/css">
.tdp
{
border-bottom: 1 solid #000000;
border-left: 1 solid #000000;
border-right: 0 solid #ffffff;
border-top: 0 solid #ffffff;
}
.tabp
{
border-color: #000000 #000000 #000000 #000000;
border-style: solid;
border-top-width: 2px;
border-right-width: 2px;
border-bottom-width: 1px;
border-left-width: 1px;
}
.NOPRINT
{
font-family: "宋体";
font-size: 9pt;
}
</style>
</head>
<body style="text-align:center">
<center class="Noprint" >
<object id="WebBrowser" classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2" height="0" width="0">
</object>
<input type="button" value="打印" onclick="document.all.WebBrowser.ExecWB(6,1)" />
<input type="button" value="直接打印" onclick="document.all.WebBrowser.ExecWB(6,6)" />
<input type="button" value="页面设置" onclick="document.all.WebBrowser.ExecWB(8,1)" />
<input type="button" value="打印预览" onclick="document.all.WebBrowser.ExecWB(7,1)" />
<hr align="center" width="90%" size="1" noshade style="height: 1px">
</center>
<form id="form1" runat="server">
<div style="text-align:center;margion:0px">
<asp:GridView ID="gvPrint" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
后代代码:

Code
if (!IsPostBack)
{
if (CacheData.GetCache().GetCacheData()!=null)
{
this.gvPrint.DataSource = CacheData.GetCache().GetCacheData();
this.gvPrint.DataBind();
}
else Alert("没有要打印的数据,不能打印!");
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述