diff --git a/全自动水压检测仪/App.config b/全自动水压检测仪/App.config index 447d87a..a7eaf11 100644 --- a/全自动水压检测仪/App.config +++ b/全自动水压检测仪/App.config @@ -1,5 +1,8 @@  + + + @@ -21,4 +24,4 @@ - \ No newline at end of file + diff --git a/全自动水压检测仪/DATA/ConductividyClass.cs b/全自动水压检测仪/DATA/ConductividyClass.cs index de3d94e..79806dc 100644 --- a/全自动水压检测仪/DATA/ConductividyClass.cs +++ b/全自动水压检测仪/DATA/ConductividyClass.cs @@ -8,6 +8,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using 全自动水压检测仪; +using 全自动水压检测仪.DATA; namespace 材料热传导系数 { @@ -149,12 +150,12 @@ namespace 材料热传导系数 public ConductivityRepository() { - _connectionString = "Server=localhost;Database=fullautowaterpressure;User=root;Password=123456;port=3306;charset=utf8;"; + _connectionString = DatabaseConnectionManager.ConnectionString; } public void InsertReportItems(ConductivityTestData data) { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); var sql = @"INSERT INTO normaltemperature ( @@ -197,7 +198,7 @@ VALUES } public void InsertScanItems(ScanData data) { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); var sql = @"INSERT INTO scandata @@ -223,7 +224,7 @@ standarderror) public void DeleteScanItems(int id) { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); var sql = @"delete from scandata where id=@id @@ -234,7 +235,7 @@ standarderror) public List GetScanData() { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); var sql = @"SELECT * FROM scandata @@ -246,7 +247,7 @@ standarderror) public List GetTestData() { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); var sql = @"SELECT * FROM normaltemperature @@ -259,7 +260,7 @@ standarderror) public void DeleteTestAllItems() { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); var sql = @"delete from normaltemperature @@ -271,7 +272,7 @@ standarderror) public void DeleteTestAllItems(int id) { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); var sql = @"delete from normaltemperature where id=@id @@ -282,7 +283,7 @@ standarderror) public List GetScanDataBylldh_jh(string jh) { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); var sql = @"SELECT * FROM scandata @@ -298,7 +299,7 @@ standarderror) /// 要更新的扫描数据 public void UpdateScanItem(ScanData scanData) { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); var sql = @"UPDATE scandata SET @@ -342,7 +343,7 @@ standarderror) /// 扫描数据对象 public ScanData GetScanDataById(int id) { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); var sql = @"SELECT * FROM scandata WHERE id = @id"; @@ -354,7 +355,7 @@ standarderror) { try { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); return connection.State == ConnectionState.Open; @@ -373,7 +374,7 @@ standarderror) /// public ConductivityTestData GetTestDataById(int id) { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); var sql = @"SELECT * FROM normaltemperature WHERE id = @id"; @@ -386,7 +387,7 @@ standarderror) /// public void UpdateTestData(ConductivityTestData testData) { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); var sql = @"UPDATE normaltemperature SET diff --git a/全自动水压检测仪/DATA/DatabaseConnectionManager.cs b/全自动水压检测仪/DATA/DatabaseConnectionManager.cs new file mode 100644 index 0000000..cde6f83 --- /dev/null +++ b/全自动水压检测仪/DATA/DatabaseConnectionManager.cs @@ -0,0 +1,82 @@ +using MySql.Data.MySqlClient; +using System; +using System.Configuration; + +namespace 全自动水压检测仪.DATA +{ + internal static class DatabaseConnectionManager + { + private const string ConnectionStringName = "FullAutoWaterPressure"; + private const string DefaultConnectionString = "Server=localhost;Database=fullautowaterpressure;User=root;Password=123456;port=3306;charset=utf8;"; + + private static readonly Lazy _connectionString = new Lazy(BuildConnectionString); + + public static string ConnectionString => _connectionString.Value; + + public static MySqlConnection CreateConnection() + { + return new MySqlConnection(ConnectionString); + } + + private static string BuildConnectionString() + { + string configuredConnectionString = ConfigurationManager.ConnectionStrings[ConnectionStringName]?.ConnectionString; + string rawConnectionString = string.IsNullOrWhiteSpace(configuredConnectionString) + ? DefaultConnectionString + : configuredConnectionString; + + try + { + var builder = new MySqlConnectionStringBuilder(rawConnectionString); + + if (string.IsNullOrWhiteSpace(builder.Server)) + { + builder.Server = "localhost"; + } + + if (builder.Port == 0) + { + builder.Port = 3306; + } + + if (string.IsNullOrWhiteSpace(builder.Database)) + { + builder.Database = "fullautowaterpressure"; + } + + if (string.IsNullOrWhiteSpace(builder.UserID)) + { + builder.UserID = "root"; + } + + if (builder.ConnectionTimeout == 0) + { + builder.ConnectionTimeout = 5; + } + + if (builder.DefaultCommandTimeout == 0) + { + builder.DefaultCommandTimeout = 30; + } + + if (string.IsNullOrWhiteSpace(builder.CharacterSet)) + { + builder.CharacterSet = "utf8"; + } + + builder.Pooling = true; + + if (builder.MaximumPoolSize == 0) + { + builder.MaximumPoolSize = 50; + } + + return builder.ConnectionString; + } + catch (Exception) + { + return DefaultConnectionString; + } + } + } +} diff --git a/全自动水压检测仪/DATA/DatabaseInitializer.cs b/全自动水压检测仪/DATA/DatabaseInitializer.cs index c792123..d521d2a 100644 --- a/全自动水压检测仪/DATA/DatabaseInitializer.cs +++ b/全自动水压检测仪/DATA/DatabaseInitializer.cs @@ -11,7 +11,7 @@ namespace 全自动水压检测仪.DATA /// public static class DatabaseInitializer { - private static readonly string _connectionString = "Server=localhost;Database=fullautowaterpressure;User=root;Password=123456;port=3306;charset=utf8;"; + private static readonly string _connectionString = DatabaseConnectionManager.ConnectionString; /// /// 初始化用户表和默认管理员账户 @@ -34,7 +34,7 @@ namespace 全自动水压检测仪.DATA /// public static void ForceResetDefaultUsers() { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); @@ -63,7 +63,7 @@ namespace 全自动水压检测仪.DATA /// private static void CreateUsersTable() { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); @@ -100,7 +100,7 @@ namespace 全自动水压检测仪.DATA /// private static void CreateDefaultAdminIfNotExists() { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); diff --git a/全自动水压检测仪/DATA/LoginDebugHelper.cs b/全自动水压检测仪/DATA/LoginDebugHelper.cs index 6bce43f..e6a8558 100644 --- a/全自动水压检测仪/DATA/LoginDebugHelper.cs +++ b/全自动水压检测仪/DATA/LoginDebugHelper.cs @@ -11,7 +11,7 @@ namespace 全自动水压检测仪.DATA /// public static class LoginDebugHelper { - private static readonly string _connectionString = "Server=localhost;Database=fullautowaterpressure;User=root;Password=123456;port=3306;charset=utf8;"; + private static readonly string _connectionString = DatabaseConnectionManager.ConnectionString; /// /// 测试密码加密和验证 @@ -49,7 +49,7 @@ namespace 全自动水压检测仪.DATA { try { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); @@ -82,7 +82,7 @@ namespace 全自动水压检测仪.DATA { try { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); diff --git a/全自动水压检测仪/DATA/UserRepository.cs b/全自动水压检测仪/DATA/UserRepository.cs index 7203107..75ff636 100644 --- a/全自动水压检测仪/DATA/UserRepository.cs +++ b/全自动水压检测仪/DATA/UserRepository.cs @@ -16,7 +16,7 @@ namespace 全自动水压检测仪.DATA public UserRepository() { - _connectionString = "Server=localhost;Database=fullautowaterpressure;User=root;Password=123456;port=3306;charset=utf8;"; + _connectionString = DatabaseConnectionManager.ConnectionString; } /// @@ -26,7 +26,7 @@ namespace 全自动水压检测仪.DATA /// 用户对象,不存在返回null public User GetUserByUsername(string username) { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); @@ -72,7 +72,7 @@ namespace 全自动水压检测仪.DATA /// 用户对象,不存在返回null public User GetUserById(int userId) { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); @@ -102,7 +102,7 @@ namespace 全自动水压检测仪.DATA /// 是否创建成功 public bool CreateUser(User user, string plainPassword) { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); @@ -134,7 +134,7 @@ namespace 全自动水压检测仪.DATA /// 是否更新成功 public bool UpdateUser(User user) { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); string sql = @"UPDATE sys_users @@ -160,7 +160,7 @@ namespace 全自动水压检测仪.DATA /// 是否删除成功 public bool DeleteUser(int userId) { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); string sql = @"DELETE FROM sys_users WHERE id = @id"; @@ -175,7 +175,7 @@ namespace 全自动水压检测仪.DATA /// 用户列表 public List GetAllUsers() { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); @@ -206,7 +206,7 @@ namespace 全自动水压检测仪.DATA /// 是否修改成功 public bool ChangePassword(int userId, string oldPassword, string newPassword) { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); @@ -246,7 +246,7 @@ namespace 全自动水压检测仪.DATA /// 是否重置成功 public bool ResetPassword(int userId, string newPassword) { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); @@ -276,7 +276,7 @@ namespace 全自动水压检测仪.DATA /// 是否更新成功 public bool UpdateLastLoginTime(string username) { - using (var connection = new MySqlConnection(_connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); string sql = @"UPDATE sys_users diff --git a/全自动水压检测仪/NormalTemperatureMode.cs b/全自动水压检测仪/NormalTemperatureMode.cs index a6d7b0e..3b1c45a 100644 --- a/全自动水压检测仪/NormalTemperatureMode.cs +++ b/全自动水压检测仪/NormalTemperatureMode.cs @@ -10,6 +10,7 @@ using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; +using System.Globalization; using System.Linq; using System.Net.Sockets; using System.Text; @@ -1252,59 +1253,146 @@ namespace 全自动水压检测仪 private void SaveTestResult() { - if (isAddTag) return; // 防止重复保存 + PersistCurrentTestResult("SaveTestResult"); + } + + private void PersistCurrentTestResult(string source) + { + if (isAddTag) + { + return; + } + + try + { + if (!TryBuildCurrentTestData(out ConductivityTestData newItem, out string validationError)) + { + Debug.WriteLine($"[{source}] 生成测试结果失败: {validationError}"); + SafeInvoke(() => + { + MessageBox.Show(validationError, "记录数据失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); + }); + return; + } + + _repository.InsertReportItems(newItem); + CurrentReport.Add(newItem); + + isAddTag = true; + _readTimetCompareResult?.Stop(); + } + catch (Exception ex) + { + Debug.WriteLine($"[{source}] 保存测试结果失败: {ex}"); + SafeInvoke(() => + { + MessageBox.Show( + $"保存测试结果失败:{ex.Message}\n\n请检查 MySQL 服务和数据库连接配置后重试。", + "记录数据失败", + MessageBoxButtons.OK, + MessageBoxIcon.Error); + }); + } + } + + private bool TryBuildCurrentTestData(out ConductivityTestData newItem, out string errorMessage) + { + newItem = null; + errorMessage = null; + + string initialPressureText = string.Empty; + string dwellTimeText = string.Empty; + string diffPressureText = string.Empty; + string endPressureText = string.Empty; + string temperatureText = string.Empty; + string contactNumber = string.Empty; + string itemNumber = string.Empty; + bool isNormalMode = false; SafeInvoke(() => { - uiTextBox3.Text = uiLabel14.Text; // 初始压力 - uiTextBox8.Text = uiTextBox5.Text; // 保压时间 - uiTextBox6.Text = uiLabel22.Text; // 压差 - uiTextBox7.Text = uiLabel19.Text; // 结束压力 + uiTextBox3.Text = uiLabel14.Text; + uiTextBox8.Text = uiTextBox5.Text; + uiTextBox6.Text = uiLabel22.Text; + uiTextBox7.Text = uiLabel19.Text; - // 获取联络单号和件号 - string contactNumber = uiTextBox2.Text.Trim(); - string itemNumber = uiTextBox10.Text.Trim(); - string barcode = $"{contactNumber}-{itemNumber}"; - - // 确保 starttime 有效(如果从未设置,回退为当前时间) - if (starttime == default(DateTime)) - { - starttime = DateTime.Now; - Debug.WriteLine("[Warn] starttime 未初始化,已回退为当前时间:" + starttime.ToString("o")); - } - - DateTime recordStartTime = starttime; - DateTime recordEndTime = DateTime.Now; - DateTime recordCreateTime = DateTime.Now; - - var newItem = new ConductivityTestData - { - barcode = barcode, - CreateTime = recordCreateTime, - diffpressure = uiTextBox6.Text.ToDouble(), - dwelltime = uiTextBox8.Text.ToDouble(), - temperature = uiTextBox4.Text.ToDouble(), - endpressure = uiTextBox7.Text.ToDouble(), - startpressure = uiTextBox3.Text.ToDouble(), - Type = uiLight1.State == UILightState.On ? 1 : 0, - // 新增字段 - kzh = kzh, - jh = uiTextBox10.Text, - endtime = recordEndTime, - quantity = quantity, - lldh = uiTextBox2.Text, - standarderror = standarderror, - starttime = recordStartTime, - testresult = (isValid ?? false) ? "合格" : "不合格" - }; - - CurrentReport.Add(newItem); - - _repository.InsertReportItems(newItem); + initialPressureText = uiTextBox3.Text.Trim(); + dwellTimeText = uiTextBox8.Text.Trim(); + diffPressureText = uiTextBox6.Text.Trim(); + endPressureText = uiTextBox7.Text.Trim(); + temperatureText = uiTextBox4.Text.Trim(); + contactNumber = uiTextBox2.Text.Trim(); + itemNumber = uiTextBox10.Text.Trim(); + isNormalMode = uiLight1.State == UILightState.On; }); - isAddTag = true; - _readTimetCompareResult?.Stop(); // 停止压差比较定时器 + if (!TryParseDoubleValue(initialPressureText, out double startPressure)) + { + errorMessage = $"初始压力格式无效:{initialPressureText}"; + return false; + } + + if (!TryParseDoubleValue(dwellTimeText, out double dwellTime)) + { + errorMessage = $"保压时间格式无效:{dwellTimeText}"; + return false; + } + + if (!TryParseDoubleValue(diffPressureText, out double diffPressure)) + { + errorMessage = $"压差格式无效:{diffPressureText}"; + return false; + } + + if (!TryParseDoubleValue(endPressureText, out double endPressure)) + { + errorMessage = $"结束压力格式无效:{endPressureText}"; + return false; + } + + if (!TryParseDoubleValue(temperatureText, out double temperature)) + { + errorMessage = $"温度格式无效:{temperatureText}"; + return false; + } + + if (starttime == default(DateTime)) + { + starttime = DateTime.Now; + Debug.WriteLine("[Warn] starttime 未初始化,已回退为当前时间:" + starttime.ToString("o")); + } + + DateTime recordStartTime = starttime; + DateTime recordEndTime = DateTime.Now; + DateTime recordCreateTime = DateTime.Now; + + newItem = new ConductivityTestData + { + barcode = $"{contactNumber}-{itemNumber}", + CreateTime = recordCreateTime, + diffpressure = diffPressure, + dwelltime = dwellTime, + temperature = temperature, + endpressure = endPressure, + startpressure = startPressure, + Type = isNormalMode ? 1 : 0, + kzh = kzh, + jh = itemNumber, + endtime = recordEndTime, + quantity = quantity, + lldh = contactNumber, + standarderror = standarderror, + starttime = recordStartTime, + testresult = (isValid ?? false) ? "合格" : "不合格" + }; + + return true; + } + + private static bool TryParseDoubleValue(string text, out double value) + { + return double.TryParse(text, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out value) || + double.TryParse(text, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.CurrentCulture, out value); } @@ -1455,81 +1543,7 @@ namespace 全自动水压检测仪 void BoolSignal1_OnRisingEdge() { - if (isAddTag) return; - - // 使用SafeInvoke确保UI读取操作在UI线程执行 - SafeInvoke(() => - { - uiTextBox3.Text = uiLabel14.Text;//初始压力 - uiTextBox8.Text = uiTextBox5.Text;//保压时间 - uiTextBox6.Text = uiLabel22.Text;//压差 - uiTextBox7.Text = uiLabel19.Text;//结束压力 - - // 获取联络单号和件号 - string contactNumber = uiTextBox2.Text.Trim(); - string itemNumber = uiTextBox10.Text.Trim(); - // 组合条码用于兼容性 - string barcode = $"{contactNumber}-{itemNumber}"; - - // 修复点:如果 starttime 未被正确初始化(默认值),在这里回退为当前时间 - if (starttime == default(DateTime)) - { - starttime = DateTime.Now; - Debug.WriteLine("[Warn] starttime 未初始化,已回退为当前时间:" + starttime.ToString("o")); - } - - // 统一使用局部变量,避免并发/多次调用导致不同时间写入 - DateTime recordStartTime = starttime; - DateTime recordEndTime = DateTime.Now; - DateTime recordCreateTime = DateTime.Now; - - var newItem = new ConductivityTestData - { - barcode = barcode, - CreateTime = recordCreateTime, - diffpressure = uiTextBox6.Text.ToDouble(), - dwelltime = uiTextBox8.Text.ToDouble(), - temperature = uiTextBox4.Text.ToDouble(), - endpressure = uiTextBox7.Text.ToDouble(), - startpressure = uiTextBox3.Text.ToDouble(), - Type = uiLight1.State == UILightState.On ? 1 : 0, - // 新增字段 - kzh = kzh, - jh = uiTextBox10.Text, - endtime = recordEndTime, - quantity = quantity, - lldh = uiTextBox2.Text, - standarderror = standarderror, - starttime = recordStartTime, - testresult = (isValid ?? false) ? "合格" : "不合格" - }; - - CurrentReport.Add(newItem); - - _repository.InsertReportItems(new ConductivityTestData - { - barcode = newItem.barcode, - CreateTime = newItem.CreateTime, - diffpressure = newItem.diffpressure, - dwelltime = newItem.dwelltime, - temperature = newItem.temperature, - endpressure = newItem.endpressure, - startpressure = newItem.startpressure, - Type = newItem.Type, - // 新增 - kzh = newItem.kzh, - jh = newItem.jh, - endtime = newItem.endtime, - quantity = newItem.quantity, - lldh = newItem.lldh, - standarderror = newItem.standarderror, - starttime = newItem.starttime, - testresult = newItem.testresult - }); - }); - - isAddTag = true; - _readTimetCompareResult?.Stop(); + PersistCurrentTestResult("BoolSignal1_OnRisingEdge"); } private bool TryReconnect() { @@ -1601,42 +1615,69 @@ namespace 全自动水压检测仪 _readTimerTwo?.Stop(); _alarmMonitorTimer?.Stop(); - // 检查资源是否可用 - if (_tcpClient == null || !_tcpClient.Connected || _modbusMaster == null) + try { - bool reconnectSuccess = TryReconnect(); - if (!reconnectSuccess) + if (_tcpClient == null || !_tcpClient.Connected || _modbusMaster == null) { - SafeInvoke(() => + bool reconnectSuccess = TryReconnect(); + if (!reconnectSuccess) { - MessageBox.Show("TCP连接已断开,请重新连接!", "提示"); - }); - ResumeAfterChildWindow(); - return; + SafeInvoke(() => + { + MessageBox.Show("TCP连接已断开,请重新连接!", "提示"); + }); + ResumeAfterChildWindow(); + return; + } } - } - // 复用窗口实例 - if (windowInstance == null || windowInstance.IsDisposed) - { - windowInstance = createFunc(); - windowInstance.FormClosed += (s, e) => + if (windowInstance == null || windowInstance.IsDisposed) { - ResumeAfterChildWindow(); - }; - } - - T targetWindow = windowInstance; - - SafeInvoke(() => - { - this.Hide(); - if (!targetWindow.Visible) - { - targetWindow.Show(); + windowInstance = createFunc(); + windowInstance.FormClosed += (s, e) => + { + ResumeAfterChildWindow(); + }; } - targetWindow.Activate(); - }); + + T targetWindow = windowInstance; + + SafeInvoke(() => + { + try + { + this.Hide(); + if (!targetWindow.Visible) + { + targetWindow.Show(); + } + targetWindow.Activate(); + } + catch (Exception ex) + { + Debug.WriteLine($"切换窗口失败: {ex}"); + ResumeAfterChildWindow(); + MessageBox.Show( + $"打开页面失败:{ex.Message}\n\n系统已恢复到主页面。", + "页面切换失败", + MessageBoxButtons.OK, + MessageBoxIcon.Error); + } + }); + } + catch (Exception ex) + { + Debug.WriteLine($"创建窗口失败: {ex}"); + ResumeAfterChildWindow(); + SafeInvoke(() => + { + MessageBox.Show( + $"打开页面失败:{ex.Message}\n\n系统已恢复到主页面。", + "页面切换失败", + MessageBoxButtons.OK, + MessageBoxIcon.Error); + }); + } } public void ResumeAfterChildWindow() @@ -2059,7 +2100,7 @@ namespace 全自动水压检测仪 private ScanData GetScanDataByBarcode(string jh) { - using (var connection = new MySqlConnection(_repository._connectionString)) + using (var connection = DatabaseConnectionManager.CreateConnection()) { connection.Open(); var sql = @"SELECT * FROM scandata diff --git a/全自动水压检测仪/Report.cs b/全自动水压检测仪/Report.cs index 9c3e78f..ff44931 100644 --- a/全自动水压检测仪/Report.cs +++ b/全自动水压检测仪/Report.cs @@ -29,18 +29,8 @@ namespace 全自动水压检测仪 private Button btnDelete; private ConductivityRepository _repository; public Report() + : this(new List()) { - InitializeComponent(); - SetupFormStyle(); - CreateDataGridView(); - CreateButtons(); - this.SuspendLayout(); - this.ClientSize = new System.Drawing.Size(1000, 600); - this.Name = "ReportForm"; - this.Text = "测试数据报表"; - this.StartPosition = FormStartPosition.CenterScreen; - this.ResumeLayout(false); - } public Report(List CurrentReport) @@ -55,7 +45,7 @@ namespace 全自动水压检测仪 this.Text = "测试数据报表"; this.StartPosition = FormStartPosition.CenterScreen; this.ResumeLayout(false); - this.CurrentReport = CurrentReport; + this.CurrentReport = CurrentReport ?? new List(); _repository = new ConductivityRepository(); } @@ -161,7 +151,7 @@ namespace 全自动水压检测仪 dataGridView.Columns.Add(new DataGridViewTextBoxColumn { - Name = "Id", + Name = "RowNumber", HeaderText = "序号", Width = 50, DataPropertyName = "row", // 绑定到ConductivityTestData的Id属性 @@ -455,9 +445,6 @@ namespace 全自动水压检测仪 DefaultCellStyle = { Alignment = DataGridViewContentAlignment.MiddleCenter } }; - // 添加单元格格式化事件 - dataGridView.CellFormatting += DataGridView_CellFormatting; - return column; } @@ -571,10 +558,7 @@ namespace 全自动水压检测仪 // ============ 结束设置 ============ var result = _repository.GetTestData(); - if (result != null && result.Count > 0) - { - CurrentReport = result; - } + CurrentReport = result ?? CurrentReport ?? new List(); int i = 0; CurrentReport.ForEach(x => { @@ -604,6 +588,7 @@ namespace 全自动水压检测仪 { MessageBox.Show($"加载数据失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); + BeginInvoke(new Action(Close)); } } @@ -1096,8 +1081,11 @@ namespace 全自动水压检测仪 private void Report_FormClosing(object sender, FormClosingEventArgs e) { //base.OnFormClosing(e); - dataGridView.CellFormatting -= DataGridView_CellFormatting; - dataGridView.CellClick -= DataGridViewCellClickHandler; // 移除事件 + if (dataGridView != null) + { + dataGridView.CellFormatting -= DataGridView_CellFormatting; + dataGridView.CellClick -= DataGridViewCellClickHandler; + } } } } diff --git a/全自动水压检测仪/全自动水压检测仪.csproj b/全自动水压检测仪/全自动水压检测仪.csproj index 4917aed..6414721 100644 --- a/全自动水压检测仪/全自动水压检测仪.csproj +++ b/全自动水压检测仪/全自动水压检测仪.csproj @@ -146,6 +146,7 @@ + @@ -292,4 +293,4 @@ - \ No newline at end of file +