店铺收银系统收据打印异常:提示无页面如何排查?
故障原因及修复方案
核心故障原因
- 打印预览对话框未关联打印文档
printPreviewDialog1没有绑定printDocument1,导致预览窗口无法获取要渲染的打印内容,这是直接触发“未找到页面”提示的原因。 PrintPage方法内过早清空数据
在预览阶段(用户未确认打印)就执行datafrmcheckout.Rows.Clear(),会直接清除预览依赖的数据,导致预览无内容,同时后续真实打印也会丢失数据。- 类级变量
pos的状态污染pos作为类级变量,每次打印后被重置为100,下次打印时内容会从页面下方开始绘制,可能超出可视区域,导致预览无内容。
修复后的代码示例
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { // 将pos改为方法内局部变量,避免多次打印的状态残留 int pos = 60; e.Graphics.DrawString("The Androids Dungeon", new Font("Century Gothic", 12, FontStyle.Bold), Brushes.Red, new Point(80)); e.Graphics.DrawString("ID Product Price Quantity Total", new Font("Century Gothic", 10, FontStyle.Bold), Brushes.Red, new Point(26,40)); // 先复制数据,避免原集合在遍历中被修改 var rows = datafrmcheckout.Rows.Cast<DataGridViewRow>().ToList(); foreach(DataGridViewRow row in rows) { // 跳过DataGridView自动生成的空行 if (row.IsNewRow) continue; int shopitemid = Convert.ToInt32(row.Cells["Column1"].Value); string shopname = row.Cells["Column2"].Value?.ToString() ?? ""; int shopprice = Convert.ToInt32(row.Cells["Column3"].Value); int shopquantity = Convert.ToInt32(row.Cells["Column4"].Value); int shoptotal = Convert.ToInt32(row.Cells["Column5"].Value); e.Graphics.DrawString(shopitemid.ToString(), new Font("Century Gothic", 8, FontStyle.Bold), Brushes.Blue, new Point(26, pos)); e.Graphics.DrawString(shopname, new Font("Century Gothic", 8, FontStyle.Bold), Brushes.Blue, new Point(45, pos)); e.Graphics.DrawString(shopprice.ToString(), new Font("Century Gothic", 8, FontStyle.Bold), Brushes.Blue, new Point(120, pos)); e.Graphics.DrawString(shopquantity.ToString(), new Font("Century Gothic", 8, FontStyle.Bold), Brushes.Blue, new Point(170, pos)); e.Graphics.DrawString(shoptotal.ToString(), new Font("Century Gothic", 8, FontStyle.Bold), Brushes.Blue, new Point(235, pos)); pos += 20; } e.Graphics.DrawString($"Grand Total: £ {grdtotal}", new Font("Century Gothic", 12, FontStyle.Bold), Brushes.Crimson, new Point(60, pos + 50)); e.Graphics.DrawString("***The Android Dungeon***", new Font("Century Gothic", 12, FontStyle.Bold), Brushes.Crimson, new Point(40, pos + 85)); } private void Printbt_Click(object sender, EventArgs e) { // 关键:绑定打印文档到预览对话框 printPreviewDialog1.Document = printDocument1; printDocument1.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("pprnm", 285, 600); if(printPreviewDialog1.ShowDialog() == DialogResult.OK) { // 用户确认打印后再清空数据 datafrmcheckout.Rows.Clear(); datafrmcheckout.Refresh(); grdtotal = 0; printDocument1.Print(); } }
额外优化点
- 增加
row.IsNewRow判断,避免处理DataGridView自动添加的空行 - 使用
?.ToString() ?? ""处理单元格值为null的情况,防止空引用异常 - 延迟数据清空操作到用户确认打印后,保证预览与打印的数据一致性
内容的提问来源于stack exchange,提问作者jacksonb
相关产品推荐
相关产品推荐

