Query_SOP.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using System.Windows.Forms;
  5. using System.Net;
  6. using System.Collections.Generic;
  7. using System.Threading;
  8. using System.Data;
  9. using System.Drawing.Imaging;
  10. using System.Drawing;
  11. using UAS_MES_NEW.Entity;
  12. using UAS_MES_NEW.PublicMethod;
  13. using Aspose.Cells;
  14. using UAS_MES_NEW.DataOperate;
  15. using UAS_MES_NEW.PublicForm;
  16. using Aspose.Cells.Drawing;
  17. using Aspose.Cells.Rendering;
  18. using System.Web.Script.Serialization;
  19. using Seagull.BarTender.Print;
  20. namespace UAS_MES_NEW.Query
  21. {
  22. public partial class Query_SOP : Form
  23. {
  24. DataHelper dh;
  25. string usercode;
  26. string sourcecode;
  27. DataTable Dbfind;
  28. public Query_SOP()
  29. {
  30. usercode = "";
  31. sourcecode = "";
  32. InitializeComponent();
  33. }
  34. private void Form3_Load(object sender, EventArgs e)
  35. {
  36. CheckForIllegalCrossThreadCalls = false;
  37. ps_prodcode.TableName = "productsop";
  38. ps_prodcode.SelectField = "ps_code # 流水号,ps_prodcode # SOP编号";
  39. ps_prodcode.FormName = Name;
  40. ps_prodcode.DBTitle = "SOP查询";
  41. ps_prodcode.SetValueField = new string[] { "ps_code", "ps_prodcode" };
  42. ps_prodcode.Condition = "";
  43. ps_prodcode.DbChange += nr_rule_DBChange;
  44. pr_code.TableName = "product";
  45. pr_code.SelectField = "pr_code # 产品编号,pr_detail # 产品名称,pr_spec # 产品规格";
  46. pr_code.FormName = Name;
  47. pr_code.DBTitle = "物料查询";
  48. pr_code.Condition = "pr_code not like '%LX%'";
  49. pr_code.SetValueField = new string[] { "pr_code" };
  50. dh = SystemInf.dh;
  51. }
  52. private void nr_rule_DBChange(object sender, EventArgs e)
  53. {
  54. Dbfind = ps_prodcode.ReturnData;
  55. BaseUtil.SetFormValue(this.Controls, Dbfind);
  56. }
  57. void uploadfile()
  58. {
  59. if (FilePath.Text == "")
  60. {
  61. MessageBox.Show("文件不能为空!");
  62. return;
  63. }
  64. //if (pr_code.Text == "")
  65. //{
  66. // MessageBox.Show("产品编号不能为空!");
  67. // return;
  68. //}
  69. if (JPG.Checked)
  70. {
  71. ps_prodcode.Text = FilePath.Text.Substring(FilePath.Text.LastIndexOf(@"\") + 1).Replace(".xls", "").Replace(".xlsx", "");
  72. pr_code_Leave(new object(), new EventArgs());
  73. DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where ps_prodcode='" + ps_prodcode.Text + "' ", "select");
  74. if (dt.Rows.Count == 0)
  75. {
  76. string code = LogicHandler.GetPiInoutCode("ProductSOP", "1");
  77. ps_code.Text = code;
  78. if (VaildDate.Checked)
  79. {
  80. dh.ExecuteSql("insert into productsop(ps_id,ps_code,ps_prodcode,ps_indate,ps_inman,ps_status,ps_statuscode,ps_vailddate,ps_prcode)values(productsop_seq.nextval,'" + code + "','" + ps_prodcode.Text + "',sysdate,'" + User.UserName + "','在录入','ENTERING',to_date('" + DateCode.Value.ToString("yyyy-MM-dd") + "','yyyy-mm-dd'),'" + pr_code.Text + "')", "insert");
  81. }
  82. else
  83. {
  84. dh.ExecuteSql("insert into productsop(ps_id,ps_code,ps_prodcode,ps_indate,ps_inman,ps_status,ps_statuscode,ps_prcode)values(productsop_seq.nextval,'" + code + "','" + ps_prodcode.Text + "',sysdate,'" + User.UserName + "','在录入','ENTERING','" + pr_code.Text + "')", "insert");
  85. }
  86. }
  87. else
  88. {
  89. string ps_id = dt.Rows[0]["ps_id"].ToString();
  90. dh.ExecuteSql("delete from ProductSOPdetail where psd_psid='" + ps_id + "'", "delete");
  91. ps_prodcode.Text = dt.Rows[0]["ps_prodcode"].ToString();
  92. }
  93. Workbook workbook = new Workbook(FilePath.Text);
  94. List<Worksheet> list = new List<Worksheet>();
  95. List<string> filename = new List<string>();
  96. if (VaildDate.Checked)
  97. {
  98. dh.ExecuteSql("update ProductSOP set ps_attachsop='',ps_inman='" + User.UserName + "',ps_vailddate=to_date('" + DateCode.Value.ToString("yyyy-MM-dd") + "','yyyy-mm-dd') where ps_prodcode='" + ps_prodcode.Text + "'", "update");
  99. }
  100. else
  101. {
  102. dh.ExecuteSql("update ProductSOP set ps_attachsop='',ps_inman='" + User.UserName + "' where ps_prodcode='" + ps_prodcode.Text + "'", "update");
  103. }
  104. OperatResult.AppendText("一共Sheet: " + workbook.Worksheets.Count + "\n");
  105. for (int i = 0; i < workbook.Worksheets.Count; i++)
  106. {
  107. OperatResult.AppendText("正在解析Sheet" + workbook.Worksheets[i].Name + "\n");
  108. if (JPG.Checked)
  109. {
  110. try
  111. {
  112. if (!Directory.Exists(Application.StartupPath + @"\" + ps_prodcode.Text))
  113. {
  114. Directory.CreateDirectory(Application.StartupPath + @"\" + ps_prodcode.Text);
  115. }
  116. string path = Application.StartupPath + @"\" + ps_prodcode.Text + @"\";
  117. // ========== 获取原始工作表 ==========
  118. Worksheet originalSheet = workbook.Worksheets[i];
  119. int lastColIndex = originalSheet.Cells.MaxDataColumn + 3;
  120. string lastColLetter = CellsHelper.ColumnIndexToName(lastColIndex);
  121. int headerRows = 3;
  122. int dataRowsPerPage = int.Parse(RowCount.Value.ToString());
  123. // ========== 计算数据行数 ==========
  124. int totalDataRows = 0;
  125. for (int r = headerRows; r <= originalSheet.Cells.MaxDataRow; r++)
  126. {
  127. bool hasData = false;
  128. for (int c = 0; c <= originalSheet.Cells.MaxDataColumn; c++)
  129. {
  130. if (originalSheet.Cells[r, c].Value != null && !string.IsNullOrWhiteSpace(originalSheet.Cells[r, c].Value.ToString()))
  131. {
  132. hasData = true;
  133. break;
  134. }
  135. }
  136. if (hasData)
  137. {
  138. totalDataRows++;
  139. }
  140. else
  141. {
  142. break;
  143. }
  144. }
  145. int totalRows = headerRows + totalDataRows;
  146. int totalPages = (int)Math.Ceiling((double)totalDataRows / dataRowsPerPage);
  147. int imageIndex = 1;
  148. for (int page = 0; page < totalPages; page++)
  149. {
  150. // ========== 关键修复:每次循环复制一份新的工作表 ==========
  151. // 复制原始工作表到新的临时工作表
  152. int newSheetIndex = workbook.Worksheets.Add();
  153. Worksheet she = workbook.Worksheets[newSheetIndex];
  154. she.Copy(originalSheet);
  155. she.Name = $"Temp_{page}";
  156. // 计算当前页的数据范围
  157. int dataStartRow = headerRows + page * dataRowsPerPage;
  158. int dataEndRow = Math.Min(headerRows + (page + 1) * dataRowsPerPage - 1, totalRows - 1);
  159. // ========== 删除当前页不需要的行(保留标题行 + 当前页数据行) ==========
  160. // 从下往上删除,避免索引变化
  161. for (int r = totalRows - 1; r >= 0; r--)
  162. {
  163. if (r < headerRows || (r >= dataStartRow && r <= dataEndRow))
  164. {
  165. // 保留标题行和当前页数据行
  166. continue;
  167. }
  168. else
  169. {
  170. // 删除不需要的行
  171. she.Cells.DeleteRow(r);
  172. }
  173. }
  174. // ========== 设置打印区域为整个表 ==========
  175. int newTotalRows = she.Cells.MaxDataRow + 1;
  176. //int endRow = Math.Min(startRow + rowSliceSize - 1, totalRows - 1);
  177. //// 1. 动态设置原表的打印区域(模拟切片)
  178. //if (endRow < rowSliceSize)
  179. //{
  180. // Console.WriteLine($"A{startRow + 1}:{lastColLetter}{rowSliceSize + 1}");
  181. // she.PageSetup.PrintArea = $"A{startRow + 1}:{lastColLetter}{rowSliceSize + 1}";
  182. //}
  183. //else
  184. //{
  185. // Console.WriteLine($"A{startRow + 1}:{lastColLetter}{endRow + 1}");
  186. // she.PageSetup.PrintArea = $"A{startRow + 1}:{lastColLetter}{endRow + 1}";
  187. //}
  188. string newPrintArea = $"A1:{lastColLetter}{newTotalRows}";
  189. she.PageSetup.PrintArea = newPrintArea;
  190. she.PageSetup.CenterHorizontally = true;
  191. she.PageSetup.CenterVertically = true;
  192. she.PageSetup.LeftMargin = 0;
  193. she.PageSetup.RightMargin = 0;
  194. she.PageSetup.TopMargin = 0;
  195. she.PageSetup.BottomMargin = 0;
  196. // ========== 添加图片/水印 ==========
  197. if (File.Exists(PrintPath.Text))
  198. {
  199. she.Pictures.Clear();
  200. int rowOffset = headerRows + int.Parse(Y.Value.ToString());
  201. she.Pictures.Add(rowOffset, int.Parse(X.Value.ToString()), PrintPath.Text);
  202. }
  203. // ========== 写入页脚 ==========
  204. string pageFooter = $"第 {imageIndex} 页 / 共 {totalPages} 页";
  205. she.PageSetup.SetFooter(1, pageFooter);
  206. // ========== 渲染图片 ==========
  207. ImageOrPrintOptions options = new ImageOrPrintOptions();
  208. options.ImageFormat = ImageFormat.Png;
  209. options.OnePagePerSheet = true; // 改为 true,确保只渲染一页
  210. options.PrintingPage = PrintingPageType.Default;
  211. SheetRender sr = new SheetRender(she, options);
  212. if (sr.PageCount > 0)
  213. {
  214. Bitmap bitmap = sr.ToImage(0);
  215. string imagename = $"{originalSheet.Name}_{imageIndex}.png";
  216. string imagePath = Path.Combine(path, imagename);
  217. bitmap.Save(imagePath, ImageFormat.Png);
  218. bitmap.Dispose();
  219. OperatResult.AppendText("解析图片【" + imagePath + "】" + "\n");
  220. // ========== 上传与入库 ==========
  221. Dictionary<string, object> dic = new Dictionary<string, object>();
  222. dic.Add("em_name", "管理员");
  223. dic.Add("em_code", "ADMIN");
  224. dic.Add("caller", "ProductSOP");
  225. OperatResult.AppendText("上传文件【" + imagePath + "】\n");
  226. string fp_id = UploadFilesToRemoteUrl("https://mes.lihantech.cn/mes/MEScommon/uploadFiles.action?_noc=1", imagePath, dic);
  227. string ps_id = dh.getFieldDataByCondition("ProductSOP", "ps_id", "ps_prodcode='" + ps_prodcode.Text + "'").ToString();
  228. dh.ExecuteSql("insert into ProductSOPdetail(psd_id,psd_psid,psd_attach) select ProductSOPdetail_seq.nextval,ps_id,'" + imagename + ";" + fp_id + "' from ProductSOP where ps_prodcode='" + ps_prodcode.Text + "'", "insert");
  229. }
  230. // ========== 删除临时工作表 ==========
  231. workbook.Worksheets.RemoveAt(newSheetIndex);
  232. imageIndex++;
  233. }
  234. }
  235. catch (Exception ex)
  236. {
  237. OperatResult.AppendText(ex.Message + ex.StackTrace);
  238. }
  239. }
  240. }
  241. }
  242. else if (PDF.Checked)
  243. {
  244. ps_prodcode.Text = FilePath.Text.Substring(FilePath.Text.LastIndexOf(@"\") + 1).Replace(".pdf", "");
  245. pr_code_Leave(new object(), new EventArgs());
  246. DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where ps_prodcode='" + ps_prodcode.Text + "' ", "select");
  247. if (dt.Rows.Count == 0)
  248. {
  249. string code = LogicHandler.GetPiInoutCode("ProductSOP", "1");
  250. ps_code.Text = code;
  251. if (VaildDate.Checked)
  252. {
  253. dh.ExecuteSql("insert into productsop(ps_id,ps_code,ps_prodcode,ps_indate,ps_inman,ps_status,ps_statuscode,ps_vailddate)values(productsop_seq.nextval,'" + code + "','" + ps_prodcode.Text + "',sysdate,'" + User.UserName + "','在录入','ENTERING',to_date('" + DateCode.Value.ToString("yyyy-MM-dd") + "','yyyy-mm-dd'))", "insert");
  254. }
  255. else
  256. {
  257. dh.ExecuteSql("insert into productsop(ps_id,ps_code,ps_prodcode,ps_indate,ps_inman,ps_status,ps_statuscode)values(productsop_seq.nextval,'" + code + "','" + ps_prodcode.Text + "',sysdate,'" + User.UserName + "','在录入','ENTERING')", "insert");
  258. }
  259. }
  260. else
  261. {
  262. string psid = dt.Rows[0]["ps_id"].ToString();
  263. dh.ExecuteSql("delete from ProductSOPdetail where psd_psid='" + psid + "'", "delete");
  264. ps_prodcode.Text = dt.Rows[0]["ps_prodcode"].ToString();
  265. }
  266. if (VaildDate.Checked)
  267. {
  268. dh.ExecuteSql("update ProductSOP set ps_attachsop='',ps_inman='" + User.UserName + "',ps_vailddate=to_date('" + DateCode.Value.ToString("yyyy-MM-dd") + "','yyyy-mm-dd') where ps_prodcode='" + ps_prodcode.Text + "'", "update");
  269. }
  270. else
  271. {
  272. dh.ExecuteSql("update ProductSOP set ps_attachsop='',ps_inman='" + User.UserName + "' where ps_prodcode='" + ps_prodcode.Text + "'", "update");
  273. }
  274. Dictionary<string, object> dic = new Dictionary<string, object>();
  275. dic.Add("em_name", "管理员");
  276. dic.Add("em_code", "ADMIN");
  277. dic.Add("caller", "ProductSOP");
  278. OperatResult.AppendText("上传文件【" + ps_prodcode.Text + "" + "】\n");
  279. string fp_id = UploadFilesToRemoteUrl("https://mes.lihantech.cn/mes/MEScommon/uploadFiles.action?_noc=1", FilePath.Text, dic);
  280. string ps_id = dh.getFieldDataByCondition("ProductSOP", "ps_id", "ps_prodcode='" + ps_prodcode.Text + "'").ToString();
  281. dh.ExecuteSql("insert into ProductSOPdetail(psd_id,psd_psid,psd_attach) select ProductSOPdetail_seq.nextval,ps_id,'" + ps_prodcode.Text + ";" + fp_id + "' from ProductSOP where ps_prodcode='" + ps_prodcode.Text + "'", "insert");
  282. }
  283. }
  284. /// <summary>
  285. /// 请求上传图片到阿里云
  286. /// </summary>
  287. /// <param name="url">上传地址</param>
  288. /// <param name="filepath">本地文件路径</param>
  289. /// <param name="dic">上传的数据信息</param>
  290. /// <returns></returns>
  291. public string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic)
  292. {
  293. try
  294. {
  295. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
  296. ServicePointManager.DefaultConnectionLimit = 50;
  297. string boundary = DateTime.Now.Ticks.ToString("x");
  298. byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
  299. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
  300. request.Method = "POST";
  301. request.Timeout = 10 * 10000;
  302. request.ContentType = "multipart/form-data; boundary=" + boundary;
  303. Stream rs = request.GetRequestStream();
  304. var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
  305. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
  306. if (dic != null)
  307. {
  308. foreach (string key in dic.Keys)
  309. {
  310. rs.Write(boundarybytes, 0, boundarybytes.Length);
  311. string formitem = string.Format(formdataTemplate, key, dic[key]);
  312. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  313. rs.Write(formitembytes, 0, formitembytes.Length);
  314. }
  315. }
  316. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
  317. {
  318. rs.Write(boundarybytes, 0, boundarybytes.Length);
  319. var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
  320. var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  321. rs.Write(headerbytes, 0, headerbytes.Length);
  322. using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
  323. {
  324. var buffer = new byte[1024];
  325. var bytesRead = 0;
  326. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  327. {
  328. rs.Write(buffer, 0, bytesRead);
  329. }
  330. }
  331. var cr = Encoding.UTF8.GetBytes("\r\n");
  332. rs.Write(cr, 0, cr.Length);
  333. }
  334. rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  335. var response = request.GetResponse() as HttpWebResponse;
  336. StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  337. string Content = newReader.ReadToEnd();
  338. Dictionary<string, object> dic1 = new Dictionary<string, object>();
  339. List<Dictionary<string, object>> dic2 = null;
  340. dic1 = BaseUtil.ToDictionary(Content);
  341. dic2 = dic1["data"] as List<Dictionary<string, object>>;
  342. string fp_id = "";
  343. if (dic2[0]["filepath"] != null)
  344. {
  345. fp_id = dic2[0]["filepath"].ToString();
  346. }
  347. if (response.StatusCode == HttpStatusCode.OK)
  348. {
  349. return fp_id;
  350. }
  351. }
  352. catch (Exception e)
  353. {
  354. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP", "上传失败", ps_prodcode.Text, "");
  355. Console.WriteLine(e.Message + e.StackTrace);
  356. }
  357. return "";
  358. }
  359. private void ChooseFile_Click(object sender, EventArgs e)
  360. {
  361. ChoosePath.Filter = "(*.xlsx)|*.xlsx|(*.xls)|*.xls|(*.pdf)|*.pdf";
  362. DialogResult result = ChoosePath.ShowDialog();
  363. if (result == DialogResult.OK)
  364. {
  365. FilePath.Text = ChoosePath.FileName;
  366. }
  367. }
  368. private void UploadSOP_Click(object sender, EventArgs e)
  369. {
  370. Thread thread = new Thread(uploadfile);
  371. SetLoadingWindow stw = new SetLoadingWindow(thread, "上传文件");
  372. stw.StartPosition = FormStartPosition.CenterScreen;
  373. stw.ShowDialog();
  374. if (JPG.Checked)
  375. {
  376. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【图片格式】", "上传成功", ps_prodcode.Text, "");
  377. }
  378. else
  379. {
  380. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【PDF格式】", "上传成功", ps_prodcode.Text, "");
  381. }
  382. }
  383. private void OperatResult_TextChanged(object sender, EventArgs e)
  384. {
  385. //OperatResult.SelectionStart = Text.Length;
  386. OperatResult.ScrollToCaret();
  387. }
  388. private void SendSop_Click(object sender, EventArgs e)
  389. {
  390. try
  391. {
  392. if (ps_prodcode.Text == "")
  393. {
  394. MessageBox.Show("线别和SOP文档不能为空");
  395. return;
  396. }
  397. if (SendDGV.Rows.Count > 0)
  398. {
  399. List<Dictionary<string, string>> listr = new List<Dictionary<string, string>>();
  400. JavaScriptSerializer jss = new JavaScriptSerializer();
  401. Dictionary<string, object> map1 = new Dictionary<string, object>();
  402. Dictionary<string, object> map = new Dictionary<string, object>();
  403. string path;
  404. string pathroot = dh.GetConfig("filePathUrl", "sys").ToString();
  405. dh.ExecuteSql("insert into soprelease(SR_ID, sr_pscode, SR_STATUS, SR_MACHINETYPE,sr_releaseman,sr_readman)" +
  406. "select soprelease_seq.nextval,'" + ps_code.Text + "',0,'" + ps_prodcode.Text + "','" + User.UserName + "',em_code from employee ", "insert");
  407. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播成功", ps_prodcode.Text, "");
  408. MessageBox.Show("文档[" + ps_prodcode.Text + "]下放成功");
  409. }
  410. else
  411. {
  412. MessageBox.Show("产品编号" + ps_prodcode.Text + "未维护SOP文档");
  413. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败,未维护SOP文档", ps_prodcode.Text, "");
  414. }
  415. }
  416. catch (Exception ex)
  417. {
  418. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败", ps_prodcode.Text, "");
  419. Console.WriteLine(ex.Message + ex.StackTrace);
  420. }
  421. }
  422. public string encryptBASE64(string key)
  423. {
  424. Console.WriteLine(key);
  425. byte[] bytes = Encoding.Default.GetBytes(key);
  426. return Convert.ToBase64String(bytes);
  427. }
  428. public static string EncodeBase64(string code_type, string code)
  429. {
  430. string encode = "";
  431. byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
  432. try
  433. {
  434. encode = Convert.ToBase64String(bytes);
  435. }
  436. catch
  437. {
  438. encode = code;
  439. }
  440. return encode;
  441. }
  442. private void pr_code_KeyDown(object sender, KeyEventArgs e)
  443. {
  444. if (e.KeyCode == Keys.Enter)
  445. {
  446. LoadPrCode();
  447. }
  448. }
  449. private BindingSource bs = new BindingSource(); // 类成员变量
  450. private void LoadPrCode()
  451. {
  452. DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where ps_prodcode='" + ps_prodcode.Text + "'", "select");
  453. if (dt.Rows.Count > 0)
  454. {
  455. string ps_id = dt.Rows[0]["ps_id"].ToString();
  456. dt = (DataTable)dh.ExecuteSql(@"select fp_name,fp_path,'' issend,psd_iskey
  457. from ProductSOPdetail
  458. left join filepath on FP_ID=substr(PSD_ATTACH,instr(PSD_ATTACH,';')+1)
  459. where psd_psid=" + ps_id, "select");
  460. if (dt.Rows.Count > 0)
  461. {
  462. // 在 UI 线程安全执行(如果已经在 UI 线程则直接调用)
  463. if (SendDGV.InvokeRequired)
  464. SendDGV.Invoke(new Action(() => BindData(dt)));
  465. else
  466. BindData(dt);
  467. }
  468. }
  469. }
  470. private void BindData(DataTable dt)
  471. {
  472. // 使用 BindingSource 避免直接置 null
  473. if (SendDGV.DataSource == null)
  474. {
  475. bs.DataSource = dt;
  476. SendDGV.DataSource = bs;
  477. }
  478. else
  479. {
  480. bs.DataSource = dt; // 直接替换内部数据,控件不会经历“无数据”状态
  481. }
  482. // 可选:刷新显示
  483. SendDGV.Refresh();
  484. }
  485. private void pr_code_Leave(object sender, EventArgs e)
  486. {
  487. //LoadPrCode();
  488. }
  489. bool AllChecked = false;
  490. private void ChooseALL_Click(object sender, EventArgs e)
  491. {
  492. if (AllChecked)
  493. {
  494. foreach (DataGridViewRow dr in SendDGV.Rows)
  495. dr.Cells[0].Value = false;
  496. AllChecked = false;
  497. }
  498. else
  499. {
  500. foreach (DataGridViewRow dr in SendDGV.Rows)
  501. dr.Cells[0].Value = true;
  502. AllChecked = true;
  503. }
  504. }
  505. private void ps_prodcode_UserControlTextChanged(object sender, EventArgs e)
  506. {
  507. LoadPrCode();
  508. }
  509. private void GetSOP_Click(object sender, EventArgs e)
  510. {
  511. LoadPrCode();
  512. }
  513. private void ChoosePrint_Click(object sender, EventArgs e)
  514. {
  515. ChoosePath.Filter = "(*.png)|*.png";
  516. DialogResult result = ChoosePath.ShowDialog();
  517. if (result == DialogResult.OK)
  518. {
  519. PrintPath.Text = ChoosePath.FileName;
  520. }
  521. }
  522. private void SendDGV_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
  523. {
  524. if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
  525. }
  526. }
  527. }