using System; using System.Data; using System.Windows.Forms; using System.Drawing.Printing; using System.Linq; using System.Collections.Generic; using System.IO; using System.Text; using System.Configuration; using gregn6Lib; using BLL; using System.Drawing; namespace BarcodePrintEngine { public partial class Gy_BarcodePrint : Form { public DBHelper oCn = new DBHelper(); // 列索引常 private const int COL_ID = 0; private const int COL_BARCODE = 1; private const int COL_MATERIALCODE = 2; private const int COL_MATERIALNAME = 3; private const int COL_QTY = 4; private const int COL_ISPRINTED = 5; private const int COL_PRINTDATE = 6; private const int COL_PRINTERNAME = 7; // 报表相关 private GridppReport Report; private DataGridView _printGrid; private int _selectColIndex = -1; // 自动打印防重入标志 private bool isAutoPrinting = false; // 配置文件路径(设备别名和打印机共用) private readonly string deviceConfigPath; public Gy_BarcodePrint() { InitializeComponent(); // 设置配置文件路径 deviceConfigPath = AppDomain.CurrentDomain.BaseDirectory + "./Config/Device.config"; this.StartPosition = FormStartPosition.CenterScreen; this.Load += Gy_BarcodePrint_Load; // 从配置文件加载打印机 LoadDefaultPrinterFromConfig(); InitGrids(); // 绑定设备别名事件 txtDeviceAlias.Leave += TxtDeviceAlias_Leave; txtDeviceAlias.KeyDown += TxtDeviceAlias_KeyDown; txtDeviceAlias.TextChanged += TxtDeviceAlias_TextChanged; txtPrinter.TextChanged += TxtPrinter_TextChanged; // 初始状态:按钮禁用,定时器未启动 btnToggleAutoPrint.Enabled = false; timer1.Interval = 60000; timer1.Stop(); } #region 配置文件读写(通用) /// /// 确保配置文件存在,若不存在则创建空的 appSettings 文件 /// private void EnsureConfigFileExists(string configPath) { if (File.Exists(configPath)) return; string dir = Path.GetDirectoryName(configPath); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); string content = @" "; File.WriteAllText(configPath, content, Encoding.UTF8); } /// /// 从指定配置文件读取键值 /// private string GetConfigKey(string configPath, string key) { EnsureConfigFileExists(configPath); var config = ConfigurationManager.OpenMappedExeConfiguration( new ExeConfigurationFileMap { ExeConfigFilename = configPath }, ConfigurationUserLevel.None); return config.AppSettings.Settings[key]?.Value ?? string.Empty; } /// /// 向指定配置文件写入键值 /// private void SetConfigKey(string configPath, string key, string value) { EnsureConfigFileExists(configPath); var config = ConfigurationManager.OpenMappedExeConfiguration( new ExeConfigurationFileMap { ExeConfigFilename = configPath }, ConfigurationUserLevel.None); if (config.AppSettings.Settings[key] == null) config.AppSettings.Settings.Add(key, value); else config.AppSettings.Settings[key].Value = value; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); } #endregion #region 打印机配置(改用配置文件) /// /// 从配置文件加载默认打印机 /// private void LoadDefaultPrinterFromConfig() { string saved = GetConfigKey(deviceConfigPath, "DefaultPrinter"); if (!string.IsNullOrEmpty(saved) && PrinterSettings.InstalledPrinters.Cast().Contains(saved)) txtPrinter.Text = saved; else txtPrinter.Text = "(未选择)"; } /// /// 保存默认打印机到配置文件 /// private void SaveDefaultPrinterToConfig(string printerName) { SetConfigKey(deviceConfigPath, "DefaultPrinter", printerName); } #endregion #region 窗体加载 – 读取配置、加载数据,但不启动定时器 private void Gy_BarcodePrint_Load(object sender, EventArgs e) { // 读取设备别名 string alias = GetConfigKey(deviceConfigPath, "DeviceAlias"); txtDeviceAlias.Text = alias ?? ""; // 加载数据(按别名过滤) LoadData(); // 检查条件更新启动按钮状态 UpdateStartButtonState(); LogService.Write("条码打印程序启动,等待用户启动自动打印服务。"); } #endregion #region 启动/停止自动打印按钮 private void btnToggleAutoPrint_Click(object sender, EventArgs e) { if (timer1.Enabled) { // 正在运行 → 准备停止,先确认 DialogResult result = MessageBox.Show( "确认停止自动打印程序吗?", "确认停止", MessageBoxButtons.YesNo, MessageBoxIcon.Question ); if (result == DialogResult.Yes) { timer1.Stop(); btnToggleAutoPrint.Text = "启动"; btnToggleAutoPrint.BackColor = Color.LightGreen; LogService.Write("自动打印服务已停止。"); } // 如果用户取消,不执行任何操作 } else { // 未运行 → 启动 if (!IsPrinterAndAliasValid()) { MessageBox.Show("请先选择有效的打印机并填写设备别名。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } timer1.Start(); btnToggleAutoPrint.Text = "停止"; btnToggleAutoPrint.BackColor = Color.Orange; LogService.Write("自动打印服务已启动。"); } } /// /// 检查打印机和别名是否有效 /// private bool IsPrinterAndAliasValid() { string printer = txtPrinter.Text.Trim(); string alias = txtDeviceAlias.Text.Trim(); bool printerOk = !string.IsNullOrEmpty(printer) && printer != "(未选择)" && PrinterSettings.InstalledPrinters.Cast().Contains(printer); bool aliasOk = !string.IsNullOrEmpty(alias); return printerOk && aliasOk; } /// /// 更新启动按钮的启用状态 /// private void UpdateStartButtonState() { if (!timer1.Enabled) { // 停止状态 bool canStart = IsPrinterAndAliasValid(); btnToggleAutoPrint.Enabled = canStart; if (canStart) { btnToggleAutoPrint.Text = "启动"; btnToggleAutoPrint.BackColor = Color.LightGreen; } else { // 当条件不满足时,按钮不可用,颜色可置灰或恢复默认 btnToggleAutoPrint.Text = "启动"; btnToggleAutoPrint.BackColor = SystemColors.Control; // 或保留绿色但禁用,视觉上灰色会覆盖 } } else { // 运行状态 btnToggleAutoPrint.Enabled = true; btnToggleAutoPrint.Text = "停止"; btnToggleAutoPrint.BackColor = Color.Orange; } } private void TxtPrinter_TextChanged(object sender, EventArgs e) { if (timer1.Enabled) { timer1.Stop(); btnToggleAutoPrint.Text = "启动"; LogService.Write("打印机变更,自动打印服务已自动停止。"); } UpdateStartButtonState(); } private void TxtDeviceAlias_TextChanged(object sender, EventArgs e) { if (timer1.Enabled) { timer1.Stop(); btnToggleAutoPrint.Text = "启动"; LogService.Write("设备别名变更,自动打印服务已自动停止。"); } UpdateStartButtonState(); } #endregion #region 设备别名 – 保存与刷新 private void TxtDeviceAlias_Leave(object sender, EventArgs e) { SaveDeviceAlias(); } private void TxtDeviceAlias_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { SaveDeviceAlias(); e.SuppressKeyPress = true; } } private void SaveDeviceAlias() { string alias = txtDeviceAlias.Text.Trim(); SetConfigKey(deviceConfigPath, "DeviceAlias", alias); LoadData(); // 刷新数据 LogService.Write($"设备别名已更新为:{alias}"); } #endregion #region 定时器 Tick – 自动打印逻辑 private void timer1_Tick(object sender, EventArgs e) { if (isAutoPrinting) return; isAutoPrinting = true; try { this.Invoke(new Action(() => { string alias = txtDeviceAlias.Text.Trim(); if (string.IsNullOrEmpty(alias)) { LogService.Write("自动打印: 未设置设备别名,跳过"); return; } if (string.IsNullOrEmpty(txtPrinter.Text) || txtPrinter.Text == "(未选择)") { LogService.Write("自动打印: 未选择打印机,跳过"); return; } string templateName = GetConfigKey(AppDomain.CurrentDomain.BaseDirectory + "./Config/PWD.config", "PrintTemplate"); if (string.IsNullOrEmpty(templateName) || templateName == "undefined") { LogService.Write("自动打印: 未配置打印模板,跳过"); return; } string safeAlias = alias.Replace("'", "''"); string sql = $@" SELECT a.HItemId AS id, a.HBarCode AS 条码编号, a.HQty AS 数量, a.HIsPrintSuccess AS 是否打印成功, a.HLastPrintDate AS 打印时间, a.HPrintName AS 打印机名称 FROM Gy_BarCodeBill_Split a INNER JOIN Gy_Material b ON a.HMaterID = b.HItemID WHERE a.HIsPrintSuccess = 0 AND ISNULL(a.HPrintName,'') = '{safeAlias}' ORDER BY a.HItemId"; DataSet ds = oCn.RunProcReturn(sql, "AutoPrintQuery"); if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0) return; List barcodeList = new List(); List idList = new List(); foreach (DataRow dr in ds.Tables[0].Rows) { string barcode = dr["条码编号"].ToString().Trim(); if (string.IsNullOrEmpty(barcode)) continue; barcodeList.Add(barcode.Replace("'", "''")); idList.Add(Convert.ToInt32(dr["id"])); } if (barcodeList.Count == 0) return; string inClause = string.Join(",", barcodeList.Select(b => "'" + b + "'")); string viewSql = $@" SELECT 条码编号, 物料代码, 物料名称, 规格型号, 批号, 数量, 供应商, 组托单号, 生产日期, 源单单号 FROM h_v_IF_BarCodeBillList_Split WHERE 条码编号 IN ({inClause})"; DataSet dsView = oCn.RunProcReturn(viewSql, "AutoPrintView"); if (dsView == null || dsView.Tables.Count == 0 || dsView.Tables[0].Rows.Count == 0) return; DataTable dtPrint = new DataTable(); dtPrint.Columns.Add("条码编号", typeof(string)); dtPrint.Columns.Add("物料代码", typeof(string)); dtPrint.Columns.Add("物料名称", typeof(string)); dtPrint.Columns.Add("规格型号", typeof(string)); dtPrint.Columns.Add("批号", typeof(string)); dtPrint.Columns.Add("数量", typeof(string)); dtPrint.Columns.Add("供应商", typeof(string)); dtPrint.Columns.Add("组托单号", typeof(string)); dtPrint.Columns.Add("生产日期", typeof(string)); dtPrint.Columns.Add("源单单号", typeof(string)); foreach (DataRow dr in dsView.Tables[0].Rows) { DataRow newRow = dtPrint.NewRow(); newRow["条码编号"] = dr["条码编号"].ToString(); newRow["物料代码"] = dr["物料代码"].ToString(); newRow["物料名称"] = dr["物料名称"].ToString(); newRow["规格型号"] = dr["规格型号"].ToString(); newRow["批号"] = dr["批号"].ToString(); object qty = dr["数量"]; newRow["数量"] = qty == DBNull.Value ? "0" : Convert.ToDecimal(qty).ToString("0"); newRow["供应商"] = dr["供应商"].ToString(); newRow["组托单号"] = dr["组托单号"].ToString(); object prodDate = dr["生产日期"]; newRow["生产日期"] = prodDate == DBNull.Value ? "" : Convert.ToDateTime(prodDate).ToString("yyyy-MM-dd"); newRow["源单单号"] = dr["源单单号"].ToString(); dtPrint.Rows.Add(newRow); } DataGridView tempGrid = new DataGridView(); tempGrid.DataSource = dtPrint; DataGridViewCheckBoxColumn selectCol = new DataGridViewCheckBoxColumn(); selectCol.HeaderText = "选择"; selectCol.Name = "选择"; tempGrid.Columns.Insert(0, selectCol); foreach (DataGridViewRow row in tempGrid.Rows) { row.Cells["选择"].Value = true; } Sub_SetReport(templateName, tempGrid); Report.Printer.PrinterName = txtPrinter.Text.Trim(); //Report.PrintPreview(true); // 弹出预览窗口 Report.Print(false); if (idList.Count > 0) { string ids = string.Join(",", idList); string updateSql = $@"UPDATE Gy_BarCodeBill_Split SET HIsPrintSuccess = 1, HLastPrintDate = GETDATE() WHERE HItemId IN ({ids})"; oCn.RunProc(updateSql); } LoadData(); LogService.Write($"自动打印完成,共打印 {barcodeList.Count} 个条码。"); })); } catch (Exception ex) { LogService.Write("自动打印异常:" + ex.Message); } finally { isAutoPrinting = false; } } #endregion #region 打印机选择(使用配置文件) private void btnSelectPrinter_Click(object sender, EventArgs e) { using (PrintDialog pd = new PrintDialog()) { pd.PrinterSettings = new PrinterSettings(); if (pd.ShowDialog() == DialogResult.OK) { string printer = pd.PrinterSettings.PrinterName; txtPrinter.Text = printer; SaveDefaultPrinterToConfig(printer); } } } #endregion #region 表格初始化 private void InitGrids() { grdUnprinted.ColumnCount = 8; grdUnprinted.Columns[COL_ID].HeaderText = "ID"; grdUnprinted.Columns[COL_ID].Visible = false; grdUnprinted.Columns[COL_BARCODE].HeaderText = "条码编号"; grdUnprinted.Columns[COL_BARCODE].Width = 200; grdUnprinted.Columns[COL_MATERIALCODE].HeaderText = "物料代码"; grdUnprinted.Columns[COL_MATERIALCODE].Width = 120; grdUnprinted.Columns[COL_MATERIALNAME].HeaderText = "物料名称"; grdUnprinted.Columns[COL_MATERIALNAME].Width = 200; grdUnprinted.Columns[COL_QTY].HeaderText = "数量"; grdUnprinted.Columns[COL_QTY].Width = 70; grdUnprinted.Columns[COL_ISPRINTED].HeaderText = "是否打印"; grdUnprinted.Columns[COL_ISPRINTED].Width = 100; grdUnprinted.Columns[COL_PRINTDATE].HeaderText = "打印时间"; grdUnprinted.Columns[COL_PRINTDATE].Width = 150; grdUnprinted.Columns[COL_PRINTERNAME].HeaderText = "打印机名称"; grdUnprinted.Columns[COL_PRINTERNAME].Width = 200; grdUnprinted.ReadOnly = true; grdUnprinted.SelectionMode = DataGridViewSelectionMode.FullRowSelect; grdUnprinted.MultiSelect = true; grdPrinted.ColumnCount = 8; grdPrinted.Columns[COL_ID].HeaderText = "ID"; grdPrinted.Columns[COL_ID].Visible = false; grdPrinted.Columns[COL_BARCODE].HeaderText = "条码编号"; grdPrinted.Columns[COL_BARCODE].Width = 200; grdPrinted.Columns[COL_MATERIALCODE].HeaderText = "物料代码"; grdPrinted.Columns[COL_MATERIALCODE].Width = 120; grdPrinted.Columns[COL_MATERIALNAME].HeaderText = "物料名称"; grdPrinted.Columns[COL_MATERIALNAME].Width = 200; grdPrinted.Columns[COL_QTY].HeaderText = "数量"; grdPrinted.Columns[COL_QTY].Width = 70; grdPrinted.Columns[COL_ISPRINTED].HeaderText = "是否打印"; grdPrinted.Columns[COL_ISPRINTED].Width = 100; grdPrinted.Columns[COL_PRINTDATE].HeaderText = "打印时间"; grdPrinted.Columns[COL_PRINTDATE].Width = 180; grdPrinted.Columns[COL_PRINTERNAME].HeaderText = "打印机名称"; grdPrinted.Columns[COL_PRINTERNAME].Width = 200; grdPrinted.ReadOnly = true; grdPrinted.SelectionMode = DataGridViewSelectionMode.FullRowSelect; grdPrinted.MultiSelect = true; } #endregion #region 加载数据 private void LoadData() { try { string alias = txtDeviceAlias.Text.Trim(); if (string.IsNullOrEmpty(alias)) { grdUnprinted.Rows.Clear(); grdPrinted.Rows.Clear(); return; } string safeAlias = alias.Replace("'", "''"); string sql = $@" SELECT a.HItemId AS id, a.HBarCode AS 条码编号, b.HNumber AS 物料代码, b.HName AS 物料名称, a.HQty AS 数量, a.HIsPrintSuccess AS 是否打印成功, a.HLastPrintDate AS 打印时间, a.HPrintName AS 打印机名称 FROM Gy_BarCodeBill_Split a INNER JOIN Gy_Material b ON a.HMaterID = b.HItemID WHERE ISNULL(a.HPrintName,'') = '{safeAlias}' ORDER BY a.HItemId"; DataSet ds = oCn.RunProcReturn(sql, "LoadBarCodeSplit"); if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0) { grdUnprinted.Rows.Clear(); grdPrinted.Rows.Clear(); return; } grdUnprinted.Rows.Clear(); grdPrinted.Rows.Clear(); foreach (DataRow dr in ds.Tables[0].Rows) { object[] rowData = new object[8]; // 8列 rowData[COL_ID] = dr["id"]; rowData[COL_BARCODE] = dr["条码编号"].ToString(); rowData[COL_MATERIALCODE] = dr["物料代码"]?.ToString() ?? ""; rowData[COL_MATERIALNAME] = dr["物料名称"]?.ToString() ?? ""; // 数量(索引4) object qtyObj = dr["数量"]; if (qtyObj == DBNull.Value || qtyObj == null) rowData[COL_QTY] = "0"; else { try { decimal qty = Convert.ToDecimal(qtyObj); rowData[COL_QTY] = qty.ToString("0"); } catch { rowData[COL_QTY] = qtyObj.ToString(); } } // 是否打印(索引5) bool isPrinted = (dr["是否打印成功"] != DBNull.Value && Convert.ToBoolean(dr["是否打印成功"])); rowData[COL_ISPRINTED] = isPrinted ? "是" : "否"; // 打印时间(索引6) rowData[COL_PRINTDATE] = dr["打印时间"] == DBNull.Value ? "" : Convert.ToDateTime(dr["打印时间"]).ToString("yyyy-MM-dd HH:mm"); // 打印机名称(索引7) rowData[COL_PRINTERNAME] = dr["打印机名称"].ToString(); if (isPrinted) grdPrinted.Rows.Add(rowData); else grdUnprinted.Rows.Add(rowData); } } catch (Exception ex) { MessageBox.Show("加载数据失败:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); LogService.Write("LoadData异常:" + ex.Message); } } #endregion #region 打印功能(通用) public static String GetConfigKey_Print(String configPath, String key) { Configuration ConfigurationInstance =ConfigurationManager.OpenMappedExeConfiguration( new ExeConfigurationFileMap() { ExeConfigFilename = configPath }, ConfigurationUserLevel.None); if (ConfigurationInstance.AppSettings.Settings[key] != null) return ConfigurationInstance.AppSettings.Settings[key].Value; else return string.Empty; } private void Sub_SetReport(string templateName, DataGridView grid) { Report = new GridppReport(); string fullPath = Pub_Class.ClsPub.AppPath + @"" + templateName + ".grf"; Report.LoadFromFile(fullPath); Report.BeforePostRecord += new _IGridppReportEvents_BeforePostRecordEventHandler(ReportBeforePostRecord); Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecordByDataTable); _printGrid = grid; _selectColIndex = Fun_GetCol("选择", grid); } private void ReportBeforePostRecord() { } private void ReportFetchRecordByDataTable() { try { DataTable dt = null; // 从 DataGridView 的数据源中获取 DataTable if (_printGrid.DataSource is DataTable) { dt = (DataTable)_printGrid.DataSource; } else if (_printGrid.DataSource is DataView) { dt = ((DataView)_printGrid.DataSource).Table; } else if (_printGrid.DataSource is BindingSource) { var bs = (BindingSource)_printGrid.DataSource; if (bs.DataSource is DataTable) dt = (DataTable)bs.DataSource; else if (bs.DataSource is DataView) dt = ((DataView)bs.DataSource).Table; } if (dt == null) { LogService.Write("打印数据源不是 DataTable/DataView,无法填充报表"); return; } Utility.FillRecordToReport(Report, dt); } catch (Exception ex) { LogService.Write("ReportFetchRecordByDataTable异常:" + ex.Message); } } private int Fun_GetCol(string colName, DataGridView grid) { for (int i = 0; i < grid.Columns.Count; i++) { if (grid.Columns[i].HeaderText == colName) return i; } return -1; } private DataGridView GetCurrentGrid() { if (tabControl1.SelectedTab == tabPageUnprinted) return grdUnprinted; else if (tabControl1.SelectedTab == tabPagePrinted) return grdPrinted; else return null; } #endregion #region 手动打印按钮 private void btnPrintBarcode_Click(object sender, EventArgs e) { DataGridView currentGrid = GetCurrentGrid(); if (currentGrid == null || currentGrid.SelectedRows.Count == 0) { MessageBox.Show("请先在当前页签中选择要打印的行。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (string.IsNullOrEmpty(txtPrinter.Text) || txtPrinter.Text == "(未选择)") { MessageBox.Show("请先选择打印机。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (!PrinterSettings.InstalledPrinters.Cast().Contains(txtPrinter.Text)) { MessageBox.Show("所选打印机不可用,请重新选择。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } string templateName = GetConfigKey_Print(AppDomain.CurrentDomain.BaseDirectory + "./Config/PWD.config", "PrintTemplate"); if (string.IsNullOrEmpty(templateName) || templateName == "undefined") { MessageBox.Show("未配置打印模板(PrintTemplate),请在配置文件中设置。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } try { List barcodeList = new List(); List idList = new List(); foreach (DataGridViewRow row in currentGrid.SelectedRows) { object barcodeObj = row.Cells[COL_BARCODE].Value; if (barcodeObj == null || barcodeObj == DBNull.Value) continue; string barcode = barcodeObj.ToString().Trim(); if (string.IsNullOrEmpty(barcode)) continue; object idObj = row.Cells[COL_ID].Value; if (idObj == null || idObj == DBNull.Value) continue; int id; try { id = Convert.ToInt32(idObj); } catch { continue; } barcodeList.Add(barcode.Replace("'", "''")); idList.Add(id); } if (barcodeList.Count == 0) { MessageBox.Show("选中行中无有效的条码编号。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } string inClause = string.Join(",", barcodeList.Select(b => "'" + b + "'")); string viewSql = $@" SELECT 条码编号, 物料代码, 物料名称, 规格型号, 批号, 数量, 供应商, 组托单号, 生产日期, 源单单号 FROM h_v_IF_BarCodeBillList_Split WHERE 条码编号 IN ({inClause})"; DataSet dsView = oCn.RunProcReturn(viewSql, "ViewData"); if (dsView == null || dsView.Tables.Count == 0 || dsView.Tables[0].Rows.Count == 0) { MessageBox.Show("未查询到有效的条码详情,请检查数据。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } DataTable dtPrint = new DataTable(); dtPrint.Columns.Add("条码编号", typeof(string)); dtPrint.Columns.Add("物料代码", typeof(string)); dtPrint.Columns.Add("物料名称", typeof(string)); dtPrint.Columns.Add("规格型号", typeof(string)); dtPrint.Columns.Add("批号", typeof(string)); dtPrint.Columns.Add("数量", typeof(string)); dtPrint.Columns.Add("供应商", typeof(string)); dtPrint.Columns.Add("组托单号", typeof(string)); dtPrint.Columns.Add("生产日期", typeof(string)); dtPrint.Columns.Add("源单单号", typeof(string)); foreach (DataRow dr in dsView.Tables[0].Rows) { DataRow newRow = dtPrint.NewRow(); newRow["条码编号"] = dr["条码编号"].ToString(); newRow["物料代码"] = dr["物料代码"].ToString(); newRow["物料名称"] = dr["物料名称"].ToString(); newRow["规格型号"] = dr["规格型号"].ToString(); newRow["批号"] = dr["批号"].ToString(); object qty = dr["数量"]; newRow["数量"] = qty == DBNull.Value ? "0" : Convert.ToDecimal(qty).ToString("0"); newRow["供应商"] = dr["供应商"].ToString(); newRow["组托单号"] = dr["组托单号"].ToString(); object prodDate = dr["生产日期"]; newRow["生产日期"] = prodDate == DBNull.Value ? "" : Convert.ToDateTime(prodDate).ToString("yyyy-MM-dd"); newRow["源单单号"] = dr["源单单号"].ToString(); dtPrint.Rows.Add(newRow); } DataGridView tempGrid = new DataGridView(); tempGrid.DataSource = dtPrint; DataGridViewCheckBoxColumn selectCol = new DataGridViewCheckBoxColumn(); selectCol.HeaderText = "选择"; selectCol.Name = "选择"; tempGrid.Columns.Insert(0, selectCol); foreach (DataGridViewRow row in tempGrid.Rows) { row.Cells["选择"].Value = true; } Sub_SetReport(templateName, tempGrid); Report.Printer.PrinterName = txtPrinter.Text.Trim(); //Report.PrintPreview(true); // 弹出预览窗口 Report.Print(false); bool isUnprinted = (tabControl1.SelectedTab == tabPageUnprinted); if (isUnprinted && idList.Count > 0) { string ids = string.Join(",", idList); string alias = txtDeviceAlias.Text.Trim().Replace("'", "''"); string updateSql = $@"UPDATE Gy_BarCodeBill_Split SET HIsPrintSuccess = 1, HLastPrintDate = GETDATE() WHERE HItemId IN ({ids})"; oCn.RunProc(updateSql); LoadData(); } else if (!isUnprinted) { MessageBox.Show("已打印记录重新打印完成(仅打印,不改变状态)。", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); } MessageBox.Show("打印完成。", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show("打印出错:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); LogService.Write("打印异常:" + ex.Message); } } #endregion private void Form1_FormClosed(object sender, FormClosedEventArgs e) { timer1?.Stop(); timer1?.Dispose(); } } }