using CNAS_SerialPort; using CnasSynchronousCommon; using CnasSynchronusClient; using CnasSynchrousModel; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.IO; using System.Linq; using System.Windows.Forms; using System.Xml.Serialization; namespace CNAS_BalanceClient { public partial class frmBalanceMain : Form { private LaboratoryTestBLL laboratoryTestBLL = new LaboratoryTestBLL(); private BalanceMainOperation operation = new BalanceMainOperation(); private string currentDataType = "ARB";//ARB全水分;Moisture水分;Ash灰分;Volatile挥发分;Crucible坩埚;Heat发热量:Sulfur测硫;Hydrogen测氢 private string currentCrucibleDataType = "Crucible|Heat";//坩埚称样数据类型(热量;硫;元素) private Dictionary DstCrucibleGrids = new Dictionary(); private List laboratoryTests = new List(); //数据源 private List cruciblelaboratoryTests = new List(); //坩埚数据样品编号类型(界面中左侧表单数据,不存储) private List lstBalanceData = new List(); //天平端映射字段相关信息 private DataBaseInfo targetdataBase = new DataBaseInfo(); //cnas目标数据库 private SerialPortConfigInfo serialPortConfig; //连接天平的串口的相关配置信息,从本地数据库中读取 private List lstReadTxt = new List(); //天平传输过来的数据 private double OldMad1Value = 0; //用于记录未开始编辑时的旧值,便于编辑出错后的返回 private double OldMad2Value = 0; //用于记录未开始编辑时的旧值,便于编辑出错后的返回 public frmBalanceMain() { InitializeComponent(); //初始化各个datagridview控件 InitializeDatagridview(dgvQuanShuiFen); InitializeDatagridview(dgvShuiFen); InitializeDatagridview(dgvHuiFen); InitializeDatagridview(dgvHuiFaFen); InitializeDatagridview(dgvWeighing); InitializeDatagridview(dgvCrucibleSulfur); InitializeDatagridview(dgvCrucibleElement); InitializeDatagridview(dgvCrucibleShelf); InitializeDatagridview(dgvShelfFind); if (GlobalCommonOperation.strUserName.Contains("admin")) { this.tsmMapping.Enabled = true; this.tsmPortConfig.Enabled = true; } else { this.tsmMapping.Enabled = false; this.tsmPortConfig.Enabled = false; } } private void frmBalanceMain_Load(object sender, EventArgs e) { //加载天平端字段信息 lstBalanceData = FileOperation.GetLocalBalanceData(); //加载CNAS数据库配置 targetdataBase = FileOperation.GetLocalPlatFormDB(); if (!CnasDataOperationFact.CnasDataOperation().TestConnect(targetdataBase)) { this.lblCNASDb.Visible = true; this.lblCNASDb.Text = "CNAS数据库无法正常连接..."; } else { this.lblCNASDb.Visible = false; } #region 注释------已经不再使用通过读取上次上传时间获取显示数据 //从目标库的每个表中获取中读取上次上传的最大时间 //Dictionary dictMaxTime = new Dictionary(); //foreach (var item in lstBalanceData) //{ // string strCompareTime = ""; // var query = item.syncParamasInfos.Where(s => s.IfDateField == true).ToList(); // if (query.Count == 1) // { // DataTable dtTime = CnasDataOperationFact.CnasDataOperation().GetMaxTimeByTableName(targetdataBase, item.syncParamasInfos[0].TargetTable, query[0].TargetField); // if (dtTime == null || dtTime.Rows.Count <= 0) // { // strCompareTime = "2019-01-01"; // } // else // strCompareTime = Convert.ToDateTime(dtTime.Rows[0][0].ToString()).ToString("yyyy-MM-dd HH:mm:ss"); // } // dictMaxTime.Add(GetLaboratoryValue(item.Type), strCompareTime); //} #endregion //从本地数据库中读取串口配置信息 serialPortConfig = new SericalPortConfigBLL().GetSerialPortConfigInfo(); //从本地数据库中读取所有数据 laboratoryTests = laboratoryTestBLL.GetLaboratoryTestDataByNoUpLoad(); if (laboratoryTests.Count <= 0) return; //绑定显示的datagridview BindData(); //初始化后面常用的一个参数(避免频繁swtich) DstCrucibleGrids = new Dictionary() { { "Crucible|Heat",dgvWeighing}, { "Crucible|Sulfur",dgvCrucibleSulfur}, { "Crucible|Hydrogen",dgvCrucibleElement} }; } private void tabBalance_Selected(object sender, TabControlEventArgs e) { //ARB全水分;Moisture水分;Ash灰分;Volatile挥发分;Crucible坩埚;Heat发热量:Sulfur测硫;Hydrogen测氢 operation.UpdateCurrentDataType(e, ref currentDataType); BindData(); } private void tsbDelete_Click(object sender, EventArgs e) { DeleteData(); } private void tsbSave_Click(object sender, EventArgs e) { //当前选项卡下的所有数据 List currentquery = new List(); if(currentDataType== "Crucible") currentquery = laboratoryTests.Where(s => s.DataType.StartsWith(currentDataType) && s.OperationType != null && s.OperationType != "").ToList(); else currentquery = laboratoryTests.Where(s => s.DataType == currentDataType&&s.OperationType!=null&& s.OperationType != "").ToList(); //执行存储 ReturnValue returnValue=laboratoryTestBLL.SaveLaboratoryData(currentquery); if (returnValue.StrErrorMsg!=null&&returnValue.StrErrorMsg != "") { AppLog.Error($"未保存成功:{returnValue.StrErrorMsg}"); MessageBox.Show(returnValue.StrErrorMsg, "提示"); } else if (returnValue.StrMsg!=null&&returnValue.StrMsg != "") { MessageBox.Show(returnValue.StrMsg, "提示"); //清空操作列的所有内容,避免重复操作 //int deletecount=currentquery.RemoveAll(s => (s.OperationType != null && s.OperationType.ToLower() == "delete")); //foreach (var item in currentquery) //{ // item.OperationType = ""; //} foreach (var item in currentquery) { if (item.OperationType == null) continue; if (item.OperationType == "") continue; if (item.OperationType.ToLower() == "delete") { laboratoryTests.Remove(item); } else { item.OperationType = ""; } } } } private void tsbAllSave_Click(object sender, EventArgs e) { //保存操作列不为空的数据行 var currentquery = laboratoryTests.Where(s =>s.OperationType != null && s.OperationType != "").ToList(); ReturnValue returnValue = laboratoryTestBLL.SaveLaboratoryData(currentquery); if (returnValue.StrErrorMsg != null && returnValue.StrErrorMsg != "") { MessageBox.Show(returnValue.StrErrorMsg, "提示"); AppLog.Error($"未保存成功:{returnValue.StrErrorMsg}"); } else if (returnValue.StrMsg != null && returnValue.StrMsg != "") { MessageBox.Show(returnValue.StrMsg, "提示"); //清空操作列的所有内容,避免重复操作 //int deletecount = currentquery.RemoveAll(s => (s.OperationType != null && s.OperationType.ToLower() == "delete")); //foreach (var item in currentquery) //{ // item.OperationType = ""; //} foreach (var item in currentquery) { if (item.OperationType == null) continue; if (item.OperationType == "") continue; if (item.OperationType.ToLower() == "delete") { laboratoryTests.Remove(item); } else { item.OperationType = ""; } } } } private void tsbOpenPort_Click(object sender, EventArgs e) { try { if (sPortBalance.IsOpen) { sPortBalance.Close(); tsbOpenPort.Text = "打开串口"; lblPort.Text = "串口已关闭..."; } else { sPortBalance.PortName = serialPortConfig.PortName; sPortBalance.BaudRate = serialPortConfig.BaudRate; sPortBalance.DataBits = serialPortConfig.DataBits; switch (serialPortConfig.Parity) { case "None": sPortBalance.Parity = System.IO.Ports.Parity.None; break; case "Odd": sPortBalance.Parity = System.IO.Ports.Parity.Odd; break; case "Even": sPortBalance.Parity = System.IO.Ports.Parity.Even; break; case "Mark": sPortBalance.Parity = System.IO.Ports.Parity.Mark; break; case "Space": sPortBalance.Parity = System.IO.Ports.Parity.Space; break; } switch (serialPortConfig.StopBits) { case "1": sPortBalance.StopBits = System.IO.Ports.StopBits.One; break; case "1.5": sPortBalance.StopBits = System.IO.Ports.StopBits.OnePointFive; break; case "2": sPortBalance.StopBits = System.IO.Ports.StopBits.Two; break; } switch (serialPortConfig.Handshake) { case "None": sPortBalance.Handshake = System.IO.Ports.Handshake.None; break; case "XOnXOff": sPortBalance.Handshake = System.IO.Ports.Handshake.XOnXOff; break; case "RequestToSend": sPortBalance.Handshake = System.IO.Ports.Handshake.RequestToSend; break; case "RequestToSendXOnXOff": sPortBalance.Handshake = System.IO.Ports.Handshake.RequestToSendXOnXOff; break; } sPortBalance.Open(); tsbOpenPort.Text = "关闭串口"; lblPort.Text = "串口已打开..."; } } catch (Exception ex) { sPortBalance = new System.IO.Ports.SerialPort(); System.Media.SystemSounds.Beep.Play(); tsbOpenPort.Text = "打开串口"; lblPort.Text = "串口已关闭..."; MessageBox.Show(ex.Message, "提示"); AppLog.Error($"打开串口失败:{ex.Message}"); } } private void sPortBalance_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { //读取缓冲区三次数据,类似{N +} {0.0000}{ g},这里只要第二部分的内容 try { //读取数据 //Invoke((EventHandler)(delegate //{ // string strReadTxt = sPortBalance.ReadExisting(); // //if (strReadTxt.StartsWith("N")) // //{ // // lstReadTxt.Clear(); // //} // //lstReadTxt.Add(strReadTxt); // //if (lstReadTxt.Count == 3) // //{ // // UpdateBalanceValue(lstReadTxt[1]); // //} // UpdateBalanceValue(strReadTxt); //} // ) // ); string strReceiveData = SerialPortDataReceive.ReceivePortData(this, sPortBalance, lstReadTxt); if(strReceiveData!="") UpdateBalanceValue(strReceiveData); } catch (Exception ex) { AppLog.Error($"接收数据失败:{ex.Message}"); throw ex; } } /// /// 初始化datagridview(补充) /// /// private void InitializeDatagridview(DataGridView dgv) { dgv.AutoGenerateColumns = false; } /// /// 选中最后一行 /// private void SelectLastRow() { //ARB 全水分;Moisture 水分;Ash 灰分;Volatile 挥发分;Crucible 坩埚;Heat 发热量:Sulfur 测硫;Hydrogen 测氢 switch (currentDataType) { case "ARB": dgvQuanShuiFen.CurrentCell = dgvQuanShuiFen.Rows[dgvQuanShuiFen.Rows.Count - 1].Cells[1]; break; case "Moisture": dgvShuiFen.CurrentCell = dgvShuiFen.Rows[dgvShuiFen.Rows.Count - 1].Cells[1]; break; case "Ash": dgvHuiFen.CurrentCell = dgvHuiFen.Rows[dgvHuiFen.Rows.Count - 1].Cells[1]; break; case "Volatile": dgvHuiFaFen.CurrentCell = dgvHuiFaFen.Rows[dgvHuiFaFen.Rows.Count - 1].Cells[1]; break; } } /// /// 绑定数据 /// private void BindData() { try { //ARB 全水分;Moisture 水分;Ash 灰分;Volatile 挥发分;Crucible 坩埚;Heat 发热量:Sulfur 测硫;Hydrogen 测氢 switch (currentDataType) { case "ARB": operation.BindData(dgvQuanShuiFen, laboratoryTests, currentDataType); break; case "Moisture": operation.BindData(dgvShuiFen, laboratoryTests, currentDataType); break; case "Ash": operation.BindData(dgvHuiFen, laboratoryTests, currentDataType); break; case "Volatile": operation.BindData(dgvHuiFaFen, laboratoryTests, currentDataType); break; case "Crucible": BindCrucibleData(); break; case "Heat": break; case "Sulfur": break; case "Hydrogen": break; } } catch (Exception ex) { AppLog.Error("删除数据时出错:" + ex.Message.ToString()); } } /// /// 删除数据 /// private void DeleteData() { try { switch (currentDataType) { case "ARB": operation.DeleteData(dgvQuanShuiFen, laboratoryTests, currentDataType); break; case "Moisture": operation.DeleteData(dgvShuiFen, laboratoryTests, currentDataType); break; case "Ash": operation.DeleteData(dgvHuiFen, laboratoryTests, currentDataType); break; case "Volatile": operation.DeleteData(dgvHuiFaFen, laboratoryTests, currentDataType); break; } } catch (Exception ex) { AppLog.Error("删除数据时出错:"+ex.Message.ToString()); } } private void tsmMapping_Click(object sender, EventArgs e) { frmBalanceField frmBalanceField = new frmBalanceField(lstBalanceData,targetdataBase); if (frmBalanceField.ShowDialog() == DialogResult.OK) { this.lstBalanceData = frmBalanceField.syncBalanceItems; } } /// /// 上传数据 /// /// /// private void tsbUpload_Click(object sender, EventArgs e) { //1.确定当前准备上传的数据(只上传选中部分) AppLog.Info("获取当前选中数据"); List lstSelectID = new List(); //ARB 全水分;Moisture 水分;Ash 灰分;Volatile 挥发分;Crucible 坩埚;Heat 发热量:Sulfur 测硫;Hydrogen 测氢 switch (currentDataType) { case "ARB": lstSelectID = operation.GetSelectItemID(dgvQuanShuiFen); break; case "Moisture": lstSelectID = operation.GetSelectItemID(dgvShuiFen); break; case "Ash": lstSelectID = operation.GetSelectItemID(dgvHuiFen); break; case "Volatile": lstSelectID = operation.GetSelectItemID(dgvHuiFaFen); break; } if (lstSelectID.Count <= 0) { AppLog.Info("未选中任何一条化验数据。上传结束。"); MessageBox.Show("请至少选择一条化验数据进行上传。", "提示"); return; } //找到当前上传的是对应化验项目的字段配置 var currentbalanceconfig = lstBalanceData.Where(x => GetLaboratoryValue(x.Type) == currentDataType).ToList(); if (currentbalanceconfig.Count <= 0) { MessageBox.Show("请先配置上传映射字段。", "提示"); return; } else { //检查配置的字段映射是否满足条件 if (currentbalanceconfig[0].syncParamasInfos.Count <= 0) { MessageBox.Show("请先配置上传映射字段。", "提示"); return; } } List lstError = new List(); int ErrorCount = 0; int SuccessCount = 0; int OtherCount = 0; //foreach (var banlanceitem in currentbalanceconfig) SyncBalanceItem banlanceitem = currentbalanceconfig[0]; //如果字段配置项目不跟当前界面展示的化验项目一致,跳过 if (currentDataType != GetLaboratoryValue(banlanceitem.Type)) return; //获取准备上传到数据库表结构 AppLog.Info("获取准备上传到数据库表结构"); DataTable dtTarget = CnasDataOperationFact.CnasDataOperation().GetCNASTablesStruct(banlanceitem.syncParamasInfos[0].TargetTable, targetdataBase); //将上传数据转换为上传数据的形式 AppLog.Info("将上传数据转换为上传数据格式"); string strErrorMsg = ""; bool bSuccess = true; List lstSuccessID = new List(); CnasInsertOperation insertOperation = new CnasInsertOperation(); var query = laboratoryTests.Where(s => s.DataType == GetLaboratoryValue(banlanceitem.Type)).ToList(); foreach (var laboratoryitem in query) { if (!lstSelectID.Contains(laboratoryitem.GUID)) continue; bSuccess = true; DataRow drNewTarget = dtTarget.NewRow(); //遍历映射表,把所有字段插入到目标表中 foreach (var item in banlanceitem.syncParamasInfos) { var strSourceField = item.SourceField; var strTargetField = item.TargetField; //当列名存在于数据表中时才能继续 int i = laboratoryitem.GetType().GetProperties().Where(sb => sb.Name== strSourceField).Count(); if (laboratoryitem.GetType().GetProperties().Where(sb => sb.Name== strSourceField).Count() > 0 && dtTarget.Columns.Contains(strTargetField)) { strErrorMsg = TestConvertValueToTarget(drNewTarget, laboratoryitem, strTargetField, strSourceField); if (strErrorMsg != "") { MessageBox.Show(string.Format("发生数据转换错误,请重新配置映射字段或修改字段值。错误信息如下:列【{0}】,值【{1}】,详情【{2}】", strSourceField, laboratoryitem.GetType().GetProperty(strSourceField).GetValue(laboratoryitem, null), strErrorMsg), "提示"); break; } } } if (strErrorMsg != "") { bSuccess = false; break; } //字段长度约束检测 AppLog.Info("检查上传数据合法性"); if (!CheckInputDatallegal(ConvertDataRowToTable(drNewTarget), banlanceitem)) { bSuccess = false; break; } //检查仪器标识列信息 if (dtTarget.Columns.Contains(banlanceitem.CnasInstrumentColumn)) drNewTarget[banlanceitem.CnasInstrumentColumn] = banlanceitem.GUID; else { MessageBox.Show("设置的CNAS仪器信息列没有在库中找到。","提示" ); bSuccess = false; break; } //根据固定值字段塞入数据到数据行 AppLog.Info("条件映射数据更改"); foreach (var item in banlanceitem.lstFixedValue) { if (dtTarget.Columns.Contains(item.ColumnName)) { switch (item.Condition) { case MapCondition.Equal: drNewTarget[item.ColumnName] = item.Value; break; } } } //执行插入一条数据 AppLog.Info("执行上传单条数据"); int iReturn = CnasDataOperationFact.CnasDataOperation().InsertDataToCNASTable(ConvertDataRowToTable(drNewTarget), targetdataBase, banlanceitem.syncParamasInfos, banlanceitem.CnasInstrumentColumn,banlanceitem.lstFixedValue); if (iReturn <= 0) //此时出现问题 { if (iReturn == -1) { AppLog.ServiceInfo("数据库连接中断,终止本次上传。"); break; //此时数据库连接中断,直接跳出循环,结束本次数据同步传输 } else if (iReturn == -2) //等于-2表示插入准备更新时发现数据一致,不再执行 { OtherCount++; } else { ErrorCount++; /*需要转换一下,否则会将整个dt全部写入日志*/ lstError.Add(GlobalCommonOperation.ConvertDataRowToTable(drNewTarget).Rows[0]); } bSuccess = false; } else //此时没有出现问题,1.如果本条数据未保存,将本条数据保存;2.向上传数据记录表中插入一条数据 { SuccessCount++; //存储化验数据到本地 if (!string.IsNullOrEmpty(laboratoryitem.OperationType)) { ReturnValue returnValue = laboratoryTestBLL.SaveLaboratoryData(laboratoryitem); if (!string.IsNullOrEmpty(returnValue.StrErrorMsg)) { //写入日志 AppLog.Error("上传完成后,没能正常存储数据到本地:" + returnValue.StrErrorMsg); } } //存储化验数据到化验记录表 UpLoadRecordBLL upLoadRecord = new UpLoadRecordBLL(); int ireturn=upLoadRecord.AddRecordToDatabase( new UpLoadRecord() { GUID = Guid.NewGuid().ToString(), LaboratoryTestGUID = laboratoryitem.GUID, UpLoadUser = GlobalCommonOperation.strUserName, UpLoadTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm")) } ); if (ireturn <= 0) { //写入日志 AppLog.Error($"上传完成后,没能正常存储上传记录数据到本地:LaboratoryTestGUID={laboratoryitem.GUID},UpLoadUser={GlobalCommonOperation.strUserName},UpLoadTime={Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm"))}"); } AppLog.Info("执行上传单条数据完成"); } if (bSuccess) //说明在整个上传过程中没有发生错误 { if(!lstSuccessID.Contains(laboratoryitem.GUID)) lstSuccessID.Add(laboratoryitem.GUID); } } MessageBox.Show($"上传操作完成!其中成功{SuccessCount}条,失败{ErrorCount}条,其他{OtherCount}条。"); //数据源中清空已经上传的项 if (lstSuccessID.Count >= 0) { foreach (var item in lstSuccessID) { laboratoryTests.RemoveAll(s => s.GUID == item); } BindData(); } } public bool CheckInputDatallegal(DataTable dtTarget,SyncBalanceItem banlanceitem) { bool bIfSuccess = true; CnasDataCheck check = new CnasDataCheck { DtReadyInsert = dtTarget, TargetDataBase = targetdataBase, StrTableName = banlanceitem.syncParamasInfos[0].TargetTable }; check.CheckData(); if (check.LstIllegalMsg != null && check.LstIllegalMsg.Count > 0) { var item = banlanceitem.syncParamasInfos.Where(s => s.TargetField == check.LstIllegalMsg[0].ColumnName).ToList(); if (item.Count == 1) { MessageBox.Show(string.Format("数据不满足上传条件,请修改后再上传。错误数据:当前列名【{0}】,列值【{1}】", item[0].SourceField, check.LstIllegalMsg[0].ColumnValue), "提示"); bIfSuccess = false; } else { MessageBox.Show(string.Format("数据不满足上传条件,请修改后再上传。错误数据:CNAS列名【{0}】,列值【{1}】", check.LstIllegalMsg[0].ColumnName, check.LstIllegalMsg[0].ColumnValue), "提示"); bIfSuccess = false; } } return bIfSuccess; } private string TestConvertValueToTarget(DataRow drTarget, LaboratoryTest laboratory, string strTargetColumn, string strSourceColumn) { string strErrorMsg = ""; try { drTarget[strTargetColumn] = laboratory.GetType().GetProperty(strSourceColumn).GetValue(laboratory, null); } catch (Exception ex) { strErrorMsg = ex.Message; AppLog.Error(strErrorMsg); } return strErrorMsg; } private DataTable ConvertDataRowToTable(DataRow dr) { DataTable dt = dr.Table.Clone(); DataRow drNew = dt.NewRow(); drNew.ItemArray = dr.ItemArray; dt.Rows.Add(drNew); return dt; } private string GetLaboratoryValue(string strShowName) { string strReturn = ""; switch (strShowName) { case "全水分": strReturn = "ARB"; break; case "水分": strReturn = "Moisture"; break; case "灰分": strReturn = "Ash"; break; case "挥发分": strReturn = "Volatile"; break; } return strReturn; } /// /// 此时新增一条样品化验记录 /// /// /// private void btnCodeOK_Click(object sender, EventArgs e) { //判断化验编号是否合法 if (this.txtCode.Text.Trim().Length <= 0) { MessageBox.Show("当条码为空时不能新增化验记录", "提示"); return; } //根据当前Tab页,增加新的数据 ReturnValue returnValue=operation.AddNewData(this.txtCode.Text.Trim(),currentDataType); if ((returnValue.StrErrorMsg == null || returnValue.StrErrorMsg == "") && returnValue.LstValue.Count == 1) { //填充自动编码数据 returnValue.LstValue[0].Auto_Code = operation.GetAutoCode(laboratoryTests); //显示页中新增一条数据 laboratoryTests.Add(returnValue.LstValue[0]); BindData(); //选中最后一行 SelectLastRow(); } else { MessageBox.Show("新增数据时出错:"+returnValue.StrErrorMsg, "提示"); AppLog.Error("新增数据时出错:" + returnValue.StrErrorMsg); } } /// /// 将天平端传入的值传入当前显示界面 /// /// private void UpdateBalanceValue(string strValue) { try { AppLog.Info($"接收串口信息:{strValue}"); double defaultdouble = 0; if (double.TryParse(strValue, out defaultdouble)) //接收到的数据必须可以转换成数字 { List lstIndex = new List(); //ARB 全水分;Moisture 水分;Ash 灰分;Volatile 挥发分;Crucible 坩埚;Heat 发热量:Sulfur 测硫;Hydrogen 测氢 //全水分,水分,灰分天平端上传列相同,使用同一个方法。 switch (currentDataType) { case "ARB": operation.UpdateQuanShuiFenBalanceWeight(dgvQuanShuiFen, lstIndex, defaultdouble, laboratoryTests, currentDataType); break; case "Moisture": operation.UpdateQuanShuiFenBalanceWeight(dgvShuiFen, lstIndex, defaultdouble, laboratoryTests, currentDataType); break; case "Ash": operation.UpdateQuanShuiFenBalanceWeight(dgvHuiFen, lstIndex, defaultdouble, laboratoryTests, currentDataType); break; case "Volatile": operation.UpdateVolatileBalanceWeight(dgvHuiFaFen, lstIndex, defaultdouble, laboratoryTests); break; case "Crucible": operation.UpdateCrucibleBalanceWeight(DstCrucibleGrids, dgvCrucibleShelf, defaultdouble, currentCrucibleDataType, laboratoryTests); break; } } } catch (Exception ex) { MessageBox.Show("无法正常插入天平值," + ex.Message, "提示"); AppLog.Error("无法正常插入天平值," + ex.Message); } } #region 绘制序号列 private void dgvQuanShuiFen_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { operation.DrawFirstColumnIndex(dgvQuanShuiFen,e); } private void dgvShuiFen_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { operation.DrawFirstColumnIndex(dgvShuiFen, e); } private void dgvHuiFen_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { operation.DrawFirstColumnIndex(dgvHuiFen, e); } private void dgvHuiFaFen_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { operation.DrawFirstColumnIndex(dgvHuiFaFen, e); } private void dgvWeighing_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { operation.DrawFirstColumnIndex(dgvWeighing, e); } private void dgvCrucibleSulfur_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { operation.DrawFirstColumnIndex(dgvCrucibleSulfur, e); } private void dgvCrucibleElement_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { operation.DrawFirstColumnIndex(dgvCrucibleElement, e); } private void dgvCrucibleShelf_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { operation.DrawFirstColumnIndex(dgvCrucibleShelf, e); } private void dgvShelfFind_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) { operation.DrawFirstColumnIndex(dgvShelfFind, e); } #endregion #region 编辑提交仪器编号,坩埚号 private void dgvQuanShuiFen_CellEndEdit(object sender, DataGridViewCellEventArgs e) { operation.CommitEditColumn(dgvQuanShuiFen, laboratoryTests, e); } private void dgvShuiFen_CellEndEdit(object sender, DataGridViewCellEventArgs e) { operation.CommitEditColumn(dgvShuiFen, laboratoryTests, e); if (dgvShuiFen.CurrentCell == null) return; if (dgvShuiFen.CurrentCell.Value == null) return; if (e.ColumnIndex == 11) //MAD编号 { string strInputValue = dgvShuiFen.CurrentCell.Value.ToString(); string strCurrentID = dgvShuiFen.Rows[dgvShuiFen.CurrentCell.RowIndex].Cells[0].Value.ToString(); var query = laboratoryTests.Where(s => s.GUID == strCurrentID).ToList(); if (query.Count == 1) { if (operation.CheckInputPercent(strInputValue)) { query[0].Mad = Convert.ToDouble(strInputValue); if (query[0].OperationType == null || query[0].OperationType == "") query[0].OperationType = "update"; } else { //将显示值改回初始值 dgvShuiFen.CurrentCell.Value = OldMad1Value; } } } } private void dgvHuiFen_CellEndEdit(object sender, DataGridViewCellEventArgs e) { operation.CommitEditColumn(dgvHuiFen, laboratoryTests, e); } private void dgvHuiFaFen_CellEndEdit(object sender, DataGridViewCellEventArgs e) { operation.CommitEditColumn(dgvHuiFaFen, laboratoryTests, e); if (dgvHuiFaFen.CurrentCell == null) return; if (dgvHuiFaFen.CurrentCell.Value == null) return; if (e.ColumnIndex == 9) //MAD编号 { string strInputValue = dgvHuiFaFen.CurrentCell.Value.ToString(); string strCurrentID = dgvHuiFaFen.Rows[dgvHuiFaFen.CurrentCell.RowIndex].Cells[0].Value.ToString(); var query = laboratoryTests.Where(s => s.GUID == strCurrentID).ToList(); if (query.Count == 1) { if (operation.CheckInputPercent(strInputValue)) { query[0].Mad = Convert.ToDouble(strInputValue); if (query[0].OperationType == null || query[0].OperationType == "") query[0].OperationType = "update"; } else { //将显示值改回初始值 dgvHuiFaFen.CurrentCell.Value = OldMad2Value; } } } if (e.ColumnIndex == 11) //焦特征 { string strInputValue = dgvHuiFaFen.CurrentCell.Value.ToString(); string strCurrentID = dgvHuiFaFen.Rows[dgvHuiFaFen.CurrentCell.RowIndex].Cells[0].Value.ToString(); var query = laboratoryTests.Where(s => s.GUID == strCurrentID).ToList(); if (query.Count == 1) { query[0].Cinder_Characteristics = strInputValue; if (query[0].OperationType == null || query[0].OperationType == "") query[0].OperationType = "update"; } } } #endregion private void btnAddReady_Click(object sender, EventArgs e) { //在左侧增加一条数据 //判断化验编号是否合法 string strSampleCode = this.txtSampleCode.Text.Trim(); if (this.txtSampleCode.Text.Trim().Length <= 0) { MessageBox.Show("样品编码不能为空!", "提示"); return; } //存在相同样品编码的化验数据,处理相同名称 int index = 1; while (true) { var query = cruciblelaboratoryTests.Where(s => s.Sample_Number == strSampleCode && s.DataType == currentCrucibleDataType).Count(); if (query > 0) { strSampleCode = this.txtSampleCode.Text.Trim() + "_" + index; index++; } else { break; } } //根据当前Tab页,增加新的数据 ReturnValue returnValue = operation.AddNewData(strSampleCode, currentCrucibleDataType); if ((returnValue.StrErrorMsg == null || returnValue.StrErrorMsg == "") && returnValue.LstValue.Count == 1) { //填充自动编码数据 returnValue.LstValue[0].Auto_Code = operation.GetAutoCode(laboratoryTests); //显示页中新增一条数据 cruciblelaboratoryTests.Add(returnValue.LstValue[0]); //绑定 BindCrucibleData(); } } /// /// 绑定坩埚侧数据 /// private void BindCrucibleData() { operation.BindCrucibleData(DstCrucibleGrids[currentCrucibleDataType], cruciblelaboratoryTests, currentCrucibleDataType); } private void tabCrucibleType_Selected(object sender, TabControlEventArgs e) { switch (e.TabPage.Name) { case "tabHeatValue": currentCrucibleDataType = "Crucible|Heat"; break; case "tabSulfurValue": currentCrucibleDataType = "Crucible|Sulfur"; break; case "tabElementAynic": currentCrucibleDataType = "Crucible|Hydrogen"; break; } BindCrucibleData(); //需要清空右侧列表,避免发生错误输入 dgvCrucibleShelf.Rows.Clear(); } private void btnCrucible_A_Click(object sender, EventArgs e) { operation.AddCrucibleShelfData(DstCrucibleGrids, dgvCrucibleShelf,currentCrucibleDataType,"A",laboratoryTests); } private void btnCrucible_B_Click(object sender, EventArgs e) { operation.AddCrucibleShelfData(DstCrucibleGrids, dgvCrucibleShelf, currentCrucibleDataType, "B", laboratoryTests); } private void btnCrucible_C_Click(object sender, EventArgs e) { operation.AddCrucibleShelfData(DstCrucibleGrids, dgvCrucibleShelf, currentCrucibleDataType, "C", laboratoryTests); } private void btnCrucible_D_Click(object sender, EventArgs e) { operation.AddCrucibleShelfData(DstCrucibleGrids, dgvCrucibleShelf, currentCrucibleDataType, "D", laboratoryTests); } private void tabShelf_Selected(object sender, TabControlEventArgs e) { //清空坩埚架数据 dgvCrucibleShelf.Rows.Clear(); } private void tsbHistory_Click(object sender, EventArgs e) { new frmHistory().Show(); } private void btnFind_Click(object sender, EventArgs e) { try { List lstFilterData = new List(); string strWeighingType = currentCrucibleDataType == "Crucible|Heat" ? "FRL" : (currentCrucibleDataType == "Crucible|Sulfur" ? "CLY" : "CHN"); lstFilterData = laboratoryTests.Where(s => s.WeighingType == strWeighingType).ToList(); if (dtpEndDate.Value >= dtpStartTime.Value) lstFilterData = lstFilterData.Where(s => s.OperaDateTime != null && s.OperaDateTime > dtpStartTime.Value && s.OperaDateTime < dtpEndDate.Value).ToList(); if (this.txtShelfFind.Text.Trim() != "") lstFilterData = lstFilterData.Where(s => s.Sample_Number == this.txtShelfFind.Text.Trim()).ToList(); dgvShelfFind.DataSource = new BindingList(); dgvShelfFind.DataSource = new BindingList(lstFilterData); } catch (Exception ex) { MessageBox.Show("查找时发生错误:" + ex.Message, "提示"); AppLog.Error("查找时发生错误:" + ex.Message); } } private void dgvQuanShuiFen_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.ColumnIndex == 10)//百分比字段 { new QuanShuiFenUIOperation().UpdateARBPercentColumn(dgvQuanShuiFen, laboratoryTests,e.RowIndex); } } private void dgvShuiFen_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.ColumnIndex == 10) //减量,百分比字段更新 { new ShuiFenUIOperation().UpdateMoisturePercentColumn(dgvShuiFen, laboratoryTests, e.RowIndex); } } private void dgvHuiFen_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.ColumnIndex == 10) //减量,百分比字段更新 { new HuiFenUIOperation().UpdateAshPercentColumn(dgvHuiFen, laboratoryTests, e.RowIndex); } } private void dgvHuiFaFen_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.ColumnIndex == 10) //减量,百分比字段更新 { new HuiFaFenUIOperation().UpdateVolatilePercentColumn(dgvHuiFaFen, laboratoryTests, e.RowIndex); } } private void dgvShuiFen_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) { if (e.ColumnIndex == 11) //MAD编号 { string strCurrentID = dgvShuiFen.Rows[dgvShuiFen.CurrentCell.RowIndex].Cells[0].Value.ToString(); var query = laboratoryTests.Where(s => s.GUID == strCurrentID).ToList(); if (query.Count == 1) { OldMad1Value = query[0].Mad; } } } private void dgvHuiFaFen_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) { if (e.ColumnIndex == 9) //MAD编号 { string strCurrentID = dgvHuiFaFen.Rows[dgvHuiFaFen.CurrentCell.RowIndex].Cells[0].Value.ToString(); var query = laboratoryTests.Where(s => s.GUID == strCurrentID).ToList(); if (query.Count == 1) { OldMad2Value = query[0].Mad; } } } private void dgvShuiFen_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { if (dgvShuiFen.CurrentCell.ColumnIndex == 11) //MAD列,手动输入只能是数字或百分比 { e.Control.KeyPress -= new KeyPressEventHandler(EditingControl_KeyPress); e.Control.KeyPress += new KeyPressEventHandler(EditingControl_KeyPress); } } private void dgvHuiFaFen_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { if (dgvHuiFaFen.CurrentCell.ColumnIndex == 9) //MAD列,手动输入只能是数字或百分比 { e.Control.KeyPress -= new KeyPressEventHandler(EditingControl_KeyPress); e.Control.KeyPress += new KeyPressEventHandler(EditingControl_KeyPress); } } private void EditingControl_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar != 8 && !Char.IsDigit(e.KeyChar) && e.KeyChar != '.') { e.Handled = true; MessageBox.Show("请输入数字与小数点", "提示"); } } //用户catch发生的错误 private void dgvShuiFen_DataError(object sender, DataGridViewDataErrorEventArgs e) { } //用户catch发生的错误 private void dgvHuiFaFen_DataError(object sender, DataGridViewDataErrorEventArgs e) { } private void btnDeleteShelf_Click(object sender, EventArgs e) { //当前选中项i if (dgvCrucibleShelf.CurrentCell == null) return; if (dgvCrucibleShelf.Rows[dgvCrucibleShelf.CurrentCell.RowIndex].Cells[0].Value == null) return; string strID = dgvCrucibleShelf.Rows[dgvCrucibleShelf.CurrentCell.RowIndex].Cells[0].Value.ToString(); //删除数据源数据 var queryitem = laboratoryTests.Where(s => s.GUID == strID).ToList(); if (queryitem.Count == 1) { queryitem[0].OperationType = "delete"; //删除显示数据 dgvCrucibleShelf.Rows[dgvCrucibleShelf.CurrentCell.RowIndex].Cells["Shelf_ID"].Value = ""; dgvCrucibleShelf.Rows[dgvCrucibleShelf.CurrentCell.RowIndex].Cells["Shelf_SampleNumber"].Value = ""; dgvCrucibleShelf.Rows[dgvCrucibleShelf.CurrentCell.RowIndex].Cells["Shelf_WeighingType"].Value = ""; dgvCrucibleShelf.Rows[dgvCrucibleShelf.CurrentCell.RowIndex].Cells["Shelf_SampleWeight"].Value = ""; dgvCrucibleShelf.Rows[dgvCrucibleShelf.CurrentCell.RowIndex].Cells["Shelf_Operator"].Value = ""; } } private void tsmPortConfig_Click(object sender, EventArgs e) { frmConfigPort frmConfig = new frmConfigPort(serialPortConfig); if (frmConfig.ShowDialog() == DialogResult.OK) { this.serialPortConfig = frmConfig.serialPortConfig; } } private void frmBalanceMain_FormClosing(object sender, FormClosingEventArgs e) { var currentquery = laboratoryTests.Where(s => s.OperationType != null && s.OperationType != "").ToList(); if (currentquery.Count() > 0) { DialogResult dr = MessageBox.Show("检测到未保存数据,是否保存?", "提示", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (dr == DialogResult.Yes) { e.Cancel = false; laboratoryTestBLL.SaveLaboratoryData(currentquery); } else if (dr == DialogResult.Cancel) { e.Cancel = true; } else { e.Cancel = false; } } } private void tsmHelper_Click(object sender, EventArgs e) { string strHelpFilePath = FileHelper.getBasePath() + @"\BalanceHelper.CHM"; System.Diagnostics.Process.Start(strHelpFilePath); } } }