Compare commits

...

10 Commits

Author SHA1 Message Date
xyy
88ef7dd3e1 2026-04-18 10:46:31 +08:00
xyy
90fcd2681a 2026-04-18 10:41:23 +08:00
GukSang.Jin
07d992d152 新增液位红色判断 2026-04-18 09:44:07 +08:00
xyy
cd1bee5c1e 2026-04-18 09:11:19 +08:00
GukSang.Jin
2eab2f3a1b 生产BUG修改 2026-04-17 10:45:45 +08:00
xyy
4d15257e9b 2026-03-23 10:18:09 +08:00
GukSang.Jin
052af5f895 更新123 2026-03-16 14:49:05 +08:00
GukSang.Jin
bb7204d13a 更新状态 2026-03-16 14:36:46 +08:00
GukSang.Jin
235d0b7442 1111 2026-03-14 17:28:34 +08:00
GukSang.Jin
3336dd08ab 更新 2026-03-14 17:12:25 +08:00
13 changed files with 786 additions and 497 deletions

View File

@@ -1,5 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="FullAutoWaterPressure" connectionString="Server=localhost;Database=fullautowaterpressure;User=root;Password=123456;port=3306;charset=utf8;" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
@@ -21,4 +24,4 @@
<add key="AllowModified" value="1" />
<!--1允许修改报表0不允许修改报表-->
</appSettings>
</configuration>
</configuration>

View File

@@ -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<ScanData> 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<ConductivityTestData> 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
@@ -268,9 +269,21 @@ standarderror)
}
}
public void DeleteTestAllItems(int id)
{
using (var connection = DatabaseConnectionManager.CreateConnection())
{
connection.Open();
var sql = @"delete from normaltemperature where id=@id
";
connection.Execute(sql, new { id });
}
}
public List<ScanData> GetScanDataBylldh_jh(string jh)
{
using (var connection = new MySqlConnection(_connectionString))
using (var connection = DatabaseConnectionManager.CreateConnection())
{
connection.Open();
var sql = @"SELECT * FROM scandata
@@ -286,7 +299,7 @@ standarderror)
/// <param name="scanData">要更新的扫描数据</param>
public void UpdateScanItem(ScanData scanData)
{
using (var connection = new MySqlConnection(_connectionString))
using (var connection = DatabaseConnectionManager.CreateConnection())
{
connection.Open();
var sql = @"UPDATE scandata SET
@@ -330,7 +343,7 @@ standarderror)
/// <returns>扫描数据对象</returns>
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";
@@ -342,7 +355,7 @@ standarderror)
{
try
{
using (var connection = new MySqlConnection(_connectionString))
using (var connection = DatabaseConnectionManager.CreateConnection())
{
connection.Open();
return connection.State == ConnectionState.Open;
@@ -361,7 +374,7 @@ standarderror)
/// </summary>
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";
@@ -374,7 +387,7 @@ standarderror)
/// </summary>
public void UpdateTestData(ConductivityTestData testData)
{
using (var connection = new MySqlConnection(_connectionString))
using (var connection = DatabaseConnectionManager.CreateConnection())
{
connection.Open();
var sql = @"UPDATE normaltemperature SET

View File

@@ -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<string> _connectionString = new Lazy<string>(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;
}
}
}
}

View File

@@ -11,7 +11,7 @@ namespace 全自动水压检测仪.DATA
/// </summary>
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;
/// <summary>
/// 初始化用户表和默认管理员账户
@@ -34,7 +34,7 @@ namespace 全自动水压检测仪.DATA
/// </summary>
public static void ForceResetDefaultUsers()
{
using (var connection = new MySqlConnection(_connectionString))
using (var connection = DatabaseConnectionManager.CreateConnection())
{
connection.Open();
@@ -63,7 +63,7 @@ namespace 全自动水压检测仪.DATA
/// </summary>
private static void CreateUsersTable()
{
using (var connection = new MySqlConnection(_connectionString))
using (var connection = DatabaseConnectionManager.CreateConnection())
{
connection.Open();
@@ -100,7 +100,7 @@ namespace 全自动水压检测仪.DATA
/// </summary>
private static void CreateDefaultAdminIfNotExists()
{
using (var connection = new MySqlConnection(_connectionString))
using (var connection = DatabaseConnectionManager.CreateConnection())
{
connection.Open();

View File

@@ -11,7 +11,7 @@ namespace 全自动水压检测仪.DATA
/// </summary>
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;
/// <summary>
/// 测试密码加密和验证
@@ -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();

View File

@@ -16,7 +16,7 @@ namespace 全自动水压检测仪.DATA
public UserRepository()
{
_connectionString = "Server=localhost;Database=fullautowaterpressure;User=root;Password=123456;port=3306;charset=utf8;";
_connectionString = DatabaseConnectionManager.ConnectionString;
}
/// <summary>
@@ -26,7 +26,7 @@ namespace 全自动水压检测仪.DATA
/// <returns>用户对象不存在返回null</returns>
public User GetUserByUsername(string username)
{
using (var connection = new MySqlConnection(_connectionString))
using (var connection = DatabaseConnectionManager.CreateConnection())
{
connection.Open();
@@ -72,7 +72,7 @@ namespace 全自动水压检测仪.DATA
/// <returns>用户对象不存在返回null</returns>
public User GetUserById(int userId)
{
using (var connection = new MySqlConnection(_connectionString))
using (var connection = DatabaseConnectionManager.CreateConnection())
{
connection.Open();
@@ -102,7 +102,7 @@ namespace 全自动水压检测仪.DATA
/// <returns>是否创建成功</returns>
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
/// <returns>是否更新成功</returns>
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
/// <returns>是否删除成功</returns>
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
/// <returns>用户列表</returns>
public List<User> GetAllUsers()
{
using (var connection = new MySqlConnection(_connectionString))
using (var connection = DatabaseConnectionManager.CreateConnection())
{
connection.Open();
@@ -206,7 +206,7 @@ namespace 全自动水压检测仪.DATA
/// <returns>是否修改成功</returns>
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
/// <returns>是否重置成功</returns>
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
/// <returns>是否更新成功</returns>
public bool UpdateLastLoginTime(string username)
{
using (var connection = new MySqlConnection(_connectionString))
using (var connection = DatabaseConnectionManager.CreateConnection())
{
connection.Open();
string sql = @"UPDATE sys_users

View File

@@ -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;
@@ -54,9 +55,17 @@ namespace 全自动水压检测仪
// 温度模式状态跟踪(用于防抖优化)
private bool _lastHighTempMode = false;
private bool _lastLowTempMode = false;
private bool _liquidLevelStopIssued = false;
private Panel[] _normalTempLevelBarSegments = Array.Empty<Panel>();
private Panel[] _highTempLevelBarSegments = Array.Empty<Panel>();
private ConductivityRepository _repository;
private static readonly Color LevelBarOffColor = Color.FromArgb(224, 228, 232);
private static readonly Color LevelBarNormalColor = Color.FromArgb(82, 196, 26);
private static readonly Color LevelBarAlertColor = Color.FromArgb(255, 77, 79);
private static readonly Color LevelBarFaultColor = Color.FromArgb(250, 173, 20);
#region
// 报警寄存器地址定义(根据图片内容)
private const ushort PRESSURE_PROTECTION_ADDR = 10200; // M200 压力保护大于
@@ -97,6 +106,7 @@ namespace 全自动水压检测仪
public NormalTemperatureMode()
{
InitializeComponent();
InitializeLiquidLevelStatusBars();
pressStopwatch = new Stopwatch();
// 只创建定时器,不在构造器中启动,避免在 Load 前访问未初始化的资源
_readTimer = InitTimer(); // 保存引用
@@ -112,6 +122,185 @@ namespace 全自动水压检测仪
_chartManager = new ChartManager();
}
private void InitializeLiquidLevelStatusBars()
{
HideLegacyLiquidLevelControls();
_normalTempLevelBarSegments = CreateLiquidLevelStatusBar(uiPanel23, "normalTempLevelBar");
_highTempLevelBarSegments = CreateLiquidLevelStatusBar(uiPanel31, "highTempLevelBar");
UpdateLiquidLevelStatusBar(_normalTempLevelBarSegments, false, false, "常温液位");
UpdateLiquidLevelStatusBar(_highTempLevelBarSegments, false, false, "高温液位");
}
private void HideLegacyLiquidLevelControls()
{
Control[] legacyControls =
{
uiLight13, uiLight14, uiLight15, uiLight16,
uiLabel8, uiLabel12, uiLabel16, uiLabel27,
uiLabel17, uiLabel34
};
foreach (var control in legacyControls)
{
if (control == null || control.IsDisposed)
{
continue;
}
control.Visible = false;
}
}
private Panel[] CreateLiquidLevelStatusBar(Control hostPanel, string barName)
{
if (hostPanel == null || hostPanel.IsDisposed)
{
return Array.Empty<Panel>();
}
var framePanel = new Panel
{
Name = $"{barName}Frame",
Size = new Size(78, 42),
Anchor = AnchorStyles.Top | AnchorStyles.Right,
BackColor = Color.FromArgb(208, 213, 219),
Padding = new Padding(2)
};
var segmentLayout = new TableLayoutPanel
{
Name = $"{barName}Layout",
Dock = DockStyle.Fill,
Margin = Padding.Empty,
Padding = Padding.Empty,
ColumnCount = 1,
RowCount = 3,
BackColor = Color.White
};
segmentLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
segmentLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 33.3333F));
segmentLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 33.3333F));
segmentLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 33.3334F));
var segments = new Panel[3];
for (int index = 0; index < segments.Length; index++)
{
var segment = new Panel
{
Name = $"{barName}Segment{index}",
Dock = DockStyle.Fill,
Margin = new Padding(1),
BackColor = LevelBarOffColor
};
segments[index] = segment;
segmentLayout.Controls.Add(segment, 0, 2 - index);
}
framePanel.Controls.Add(segmentLayout);
hostPanel.Controls.Add(framePanel);
framePanel.BringToFront();
void RepositionStatusBar(object sender, EventArgs e)
{
framePanel.Location = new Point(
Math.Max(64, hostPanel.ClientSize.Width - framePanel.Width - 16),
Math.Max(3, (hostPanel.ClientSize.Height - framePanel.Height) / 2));
}
hostPanel.SizeChanged += RepositionStatusBar;
RepositionStatusBar(hostPanel, EventArgs.Empty);
return segments;
}
private static bool TryGetCoilValue(bool[] coilData, out bool value)
{
if (coilData != null && coilData.Length > 0)
{
value = coilData[0];
return true;
}
value = false;
return false;
}
private void UpdateLiquidLevelStatusBar(Panel[] segments, bool sensorA, bool sensorB, string barName)
{
if (segments == null || segments.Length != 3)
{
return;
}
Color[] colors;
if (!sensorA && !sensorB)
{
colors = new[] { LevelBarAlertColor, LevelBarAlertColor, LevelBarAlertColor };
}
else if (sensorA && !sensorB)
{
colors = new[] { LevelBarNormalColor, LevelBarNormalColor, LevelBarOffColor };
}
else if (sensorA && sensorB)
{
colors = new[] { LevelBarNormalColor, LevelBarNormalColor, LevelBarAlertColor };
}
else
{
colors = new[] { LevelBarFaultColor, LevelBarFaultColor, LevelBarFaultColor };
Debug.WriteLine($"[LiquidLevelStatusBar] 检测到异常液位组合: {barName}, A={sensorA}, B={sensorB}");
}
for (int index = 0; index < segments.Length; index++)
{
if (segments[index] == null || segments[index].IsDisposed)
{
continue;
}
segments[index].BackColor = colors[index];
}
}
private static bool IsLiquidLevelAlertState(bool sensorA, bool sensorB)
{
return (!sensorA && !sensorB) || (sensorA && sensorB);
}
private bool IsAnyLiquidLevelBarInAlert()
{
bool[] normalLow = _modbusMaster?.ReadCoils(1, 10042, 1);
bool[] normalHigh = _modbusMaster?.ReadCoils(1, 10043, 1);
bool[] highLow = _modbusMaster?.ReadCoils(1, 10040, 1);
bool[] highHigh = _modbusMaster?.ReadCoils(1, 10041, 1);
bool normalAlert = TryGetCoilValue(normalLow, out bool normalSensorA) &&
TryGetCoilValue(normalHigh, out bool normalSensorB) &&
IsLiquidLevelAlertState(normalSensorA, normalSensorB);
bool highAlert = TryGetCoilValue(highLow, out bool highSensorA) &&
TryGetCoilValue(highHigh, out bool highSensorB) &&
IsLiquidLevelAlertState(highSensorA, highSensorB);
return normalAlert || highAlert;
}
private void StopTestForLiquidLevelAlert(string source)
{
if (_liquidLevelStopIssued)
{
return;
}
_liquidLevelStopIssued = true;
Debug.WriteLine($"[{source}] 检测到液位红色报警,执行停止测试");
ma?.BtnClickFunctionForNew(Function.ButtonType., 10082);
}
private System.Windows.Forms.Timer InitAlarmMonitorTimer()
{
var timer = new System.Windows.Forms.Timer()
@@ -501,70 +690,36 @@ namespace 全自动水压检测仪
// if (percentage > 100) percentage = 100;
bool[] a = _modbusMaster?.ReadCoils(1, 10042, 1);
bool[] b = _modbusMaster?.ReadCoils(1, 10043, 1);
bool[] cc = _modbusMaster?.ReadCoils(1, 10040, 1);
bool[] d = _modbusMaster?.ReadCoils(1, 10041, 1);
bool[] a = _modbusMaster?.ReadCoils(1, 10042, 1); // 常温低液位 0无水/1有水
bool[] b = _modbusMaster?.ReadCoils(1, 10043, 1); // 常温高液位 0无水/1有水
bool[] cc = _modbusMaster?.ReadCoils(1, 10040, 1); // 高温低液位 0无水/1有水
bool[] d = _modbusMaster?.ReadCoils(1, 10041, 1); // 高温高液位 0无水/1有水
if (a != null && a.Length > 0)
{
if (a[0])
{
uiLight13.OnColor = System.Drawing.Color.Green;//有水
}
if (TryGetCoilValue(a, out bool normalSensorA) &&
TryGetCoilValue(b, out bool normalSensorB))
{
UpdateLiquidLevelStatusBar(_normalTempLevelBarSegments, normalSensorA, normalSensorB, "常温液位");
}
else
{
uiLight13.OnColor = System.Drawing.Color.Red;
}
}
if (TryGetCoilValue(cc, out bool highSensorA) &&
TryGetCoilValue(d, out bool highSensorB))
{
UpdateLiquidLevelStatusBar(_highTempLevelBarSegments, highSensorA, highSensorB, "高温液位");
}
if (b != null && b.Length > 0)
{
if (!b[0])
{
uiLight14.OnColor = System.Drawing.Color.Green;//有水
}
#region
if (!a[0] || !cc[0])
else
{
uiLight14.OnColor = System.Drawing.Color.Red;
}
}
if (cc != null && cc.Length > 0)
{
if (cc[0])
{
uiLight16.OnColor = System.Drawing.Color.Green;//有水
}
{
ma?.BtnClickFunctionForNew(Function.ButtonType., 10082);
}
#endregion
else
{
uiLight16.OnColor = System.Drawing.Color.Red;
}
}
if (d != null && d.Length > 0)
{
if (!d[0])
{
uiLight15.OnColor = System.Drawing.Color.Green;//有水
}
//// 更新进度条
//if (uiProcessBar1 != null && !uiProcessBar1.IsDisposed)
// uiProcessBar1.Value = (int)percentage;
else
{
uiLight15.OnColor = System.Drawing.Color.Red;
}
}
//// 更新进度条
//if (uiProcessBar1 != null && !uiProcessBar1.IsDisposed)
// uiProcessBar1.Value = (int)percentage;
//uiLabel12.Text = value1.ToString("F2");
//uiLabel12.Text = value1.ToString("F2");
//}
// 初始压力
@@ -1138,59 +1293,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);
}
@@ -1341,81 +1583,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()
{
@@ -1480,61 +1648,99 @@ namespace 全自动水压检测仪
// windowInstance.Show();
//}
private void SwitchWindow<T>(T windowInstance, Func<T> createFunc) where T : UIForm
private void SwitchWindow<T>(ref T windowInstance, Func<T> createFunc) where T : UIForm
{
_isSwitchingWindow = true;
_readTimer?.Stop();
_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连接已断开请重新连接", "提示");
});
return;
SafeInvoke(() =>
{
MessageBox.Show("TCP连接已断开请重新连接", "提示");
});
ResumeAfterChildWindow();
return;
}
}
}
// 需要将 windowInstance 声明为局部变量
T localInstance = windowInstance;
// 复用窗口实例
if (localInstance == null || localInstance.IsDisposed)
{
localInstance = createFunc();
localInstance.FormClosed += (s, e) =>
if (windowInstance == null || windowInstance.IsDisposed)
{
SafeInvoke(() =>
windowInstance = createFunc();
windowInstance.FormClosed += (s, e) =>
{
_isSwitchingWindow = false;
_readTimer?.Start();
_readTimerTwo?.Start();
_alarmMonitorTimer?.Start();
this.Show();
this.Activate();
});
};
}
else
{
SafeInvoke(() => localInstance.Activate());
return;
}
ResumeAfterChildWindow();
};
}
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()
{
SafeInvoke(() =>
{
this.Hide();
localInstance.Show();
});
_isSwitchingWindow = false;
// 如果需要更新外部引用,可以返回实例
// return localInstance;
if (_modbusMaster != null)
{
_readTimer?.Start();
_readTimerTwo?.Start();
_alarmMonitorTimer?.Start();
}
if (!this.Visible)
{
this.Show();
}
this.Activate();
UpdateControlsVisibilityByMode();
});
}
private void NormalTemperatureMode_FormClosing(object sender, FormClosingEventArgs e)
@@ -1683,13 +1889,13 @@ namespace 全自动水压检测仪
private void EnterFunction()
{
// 长按后进入的功能
SwitchWindow(_coeffiicientsetting, () => new Coeffiicientsetting());
SwitchWindow(ref _coeffiicientsetting, () => new Coeffiicientsetting());
}
//切换报告界面
private void uiButton1_Click(object sender, EventArgs e)
{
SwitchWindow(_report, () => new Report(CurrentReport));
SwitchWindow(ref _report, () => new Report(CurrentReport));
}
//箱体温度设置
@@ -1706,6 +1912,7 @@ namespace 全自动水压检测仪
{
ma?.BtnClickFunctionForNew(Function.ButtonType., 10080);
isAddTag = false;
_liquidLevelStopIssued = false;
starttime = DateTime.Now;
// 清除图表数据,开始新的测试
_chartManager?.ClearData();
@@ -1841,7 +2048,7 @@ namespace 全自动水压检测仪
//返回录入系统
private void uiButton7_Click(object sender, EventArgs e)
{
SwitchWindow(_scanImport, () => new ScanImport());
SwitchWindow(ref _scanImport, () => new ScanImport(this));
}
@@ -1934,7 +2141,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
@@ -2203,4 +2410,4 @@ namespace 全自动水压检测仪
});
}
}
}
}

View File

@@ -29,18 +29,8 @@ namespace 全自动水压检测仪
private Button btnDelete;
private ConductivityRepository _repository;
public Report()
: this(new List<ConductivityTestData>())
{
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<ConductivityTestData> CurrentReport)
@@ -55,7 +45,7 @@ namespace 全自动水压检测仪
this.Text = "测试数据报表";
this.StartPosition = FormStartPosition.CenterScreen;
this.ResumeLayout(false);
this.CurrentReport = CurrentReport;
this.CurrentReport = CurrentReport ?? new List<ConductivityTestData>();
_repository = new ConductivityRepository();
}
@@ -121,7 +111,16 @@ namespace 全自动水压检测仪
dataGridView.Columns.Clear();
dataGridView.ScrollBars = ScrollBars.Both;
// 添加复选框列(放在最前面)
DataGridViewCheckBoxColumn selectColumn = new DataGridViewCheckBoxColumn
{
Name = "SelectColumn",
HeaderText = "选择",
Width = 50,
SortMode = DataGridViewColumnSortMode.NotSortable,
DefaultCellStyle = { Alignment = DataGridViewContentAlignment.MiddleCenter }
};
dataGridView.Columns.Add(selectColumn);
var config = ConfigurationManager.AppSettings;
if (config["AllowModified"]?.ToString() == "1")
{
@@ -152,7 +151,7 @@ namespace 全自动水压检测仪
dataGridView.Columns.Add(new DataGridViewTextBoxColumn
{
Name = "Id",
Name = "RowNumber",
HeaderText = "序号",
Width = 50,
DataPropertyName = "row", // 绑定到ConductivityTestData的Id属性
@@ -373,7 +372,7 @@ namespace 全自动水压检测仪
// 导出报表按钮
btnExport = new Button
{
Text = "导出报表",
Text = "导出选中报表",
Width = 100,
Height = 35,
Font = new Font(this.Font, FontStyle.Regular),
@@ -408,7 +407,7 @@ namespace 全自动水压检测仪
// 导出报表按钮
btnDelete = new Button
{
Text = "一键清除",
Text = "清除选中",
Width = 100,
Height = 35,
Font = new Font(this.Font, FontStyle.Regular),
@@ -446,9 +445,6 @@ namespace 全自动水压检测仪
DefaultCellStyle = { Alignment = DataGridViewContentAlignment.MiddleCenter }
};
// 添加单元格格式化事件
dataGridView.CellFormatting += DataGridView_CellFormatting;
return column;
}
@@ -562,10 +558,7 @@ namespace 全自动水压检测仪
// ============ 结束设置 ============
var result = _repository.GetTestData();
if (result != null && result.Count > 0)
{
CurrentReport = result;
}
CurrentReport = result ?? CurrentReport ?? new List<ConductivityTestData>();
int i = 0;
CurrentReport.ForEach(x =>
{
@@ -574,6 +567,13 @@ namespace 全自动水压检测仪
});
dataGridView.DataSource = CurrentReport;
foreach (DataGridViewRow row in dataGridView.Rows)
{
if (row.Cells["SelectColumn"].Value == null)
row.Cells["SelectColumn"].Value = false;
}
// 刷新显示
dataGridView.Refresh();
@@ -588,6 +588,7 @@ namespace 全自动水压检测仪
{
MessageBox.Show($"加载数据失败:{ex.Message}", "错误",
MessageBoxButtons.OK, MessageBoxIcon.Error);
BeginInvoke(new Action(Close));
}
}
@@ -684,14 +685,47 @@ namespace 全自动水压检测仪
}
}
}
/// <summary>
/// 导出报表按钮点击事件
/// </summary>
///// <summary>
///// 导出报表按钮点击事件
///// </summary>
//private void BtnExport_Click(object sender, EventArgs e)
//{
// ExportReport();
//}
private void BtnExport_Click(object sender, EventArgs e)
{
ExportReport();
}
// 获取选中的行
var selectedItems = dataGridView.Rows.Cast<DataGridViewRow>()
.Where(row => row.Cells["SelectColumn"].Value != null && (bool)row.Cells["SelectColumn"].Value)
.Select(row => row.DataBoundItem as ConductivityTestData)
.Where(item => item != null)
.ToList();
if (selectedItems.Count == 0)
{
MessageBox.Show("请至少选择一行数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
try
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel文件|*.xlsx";
saveFileDialog.Title = "导出报表";
saveFileDialog.FileName = $"测试报表_{DateTime.Now:yyyyMMdd_HHmmss}";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
ExportToExcel(saveFileDialog.FileName, selectedItems);
MessageBox.Show($"报表已成功导出到:\n{saveFileDialog.FileName}", "导出成功",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show($"导出报表失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// 返回按钮点击事件
/// </summary>
@@ -700,205 +734,141 @@ namespace 全自动水压检测仪
ReturnToMain();
}
/// <summary>
/// 返回按钮点击事件
/// </summary>
private void BtnDelete_Click(object sender, EventArgs e)
{
DialogResult ask = MessageBox.Show("此操作会清空所有历史数据,请先导出?",
"确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (ask == DialogResult.Yes)
{
CurrentReport.Clear();
dataGridView.DataSource = new List<ConductivityTestData>();
_repository.DeleteTestAllItems();
// 刷新显示
dataGridView.Refresh();
}
}
/// <summary>
/// 导出报表功能
/// </summary>
private void ExportReport()
{
//if (CurrentReport == null || CurrentReport.Count == 0)
//{
// MessageBox.Show("没有数据可以导出", "提示",
// MessageBoxButtons.OK, MessageBoxIcon.Information);
// return;
//}
try
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "CSV文件|*.csv|Excel文件|*.xlsx|文本文件|*.txt";
saveFileDialog.Title = "导出报表";
saveFileDialog.FileName = $"测试报表_{DateTime.Now:yyyyMMdd_HHmmss}";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = saveFileDialog.FileName;
//switch (Path.GetExtension(filePath).ToLower())
//{
//case ".csv":
// ExportToCsv(filePath);
// break;
//case ".txt":
// ExportToTxt(filePath);
// break;
//case ".xlsx":
ExportToExcel(filePath);
// break;
// default:
// ExportToCsv(filePath);
// break;
//}
MessageBox.Show($"报表已成功导出到:\n{filePath}", "导出成功",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show($"导出报表失败:{ex.Message}", "错误",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// 导出为Excel文件简单实现
/// </summary>
//private void ExportToExcel(string filePath)
///// <summary>
///// 返回按钮点击事件
///// </summary>
//private void BtnDelete_Click(object sender, EventArgs e)
//{
// using (var package = new ExcelPackage())
// DialogResult ask = MessageBox.Show("此操作会清空所有历史数据,请先导出?",
// "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
// if (ask == DialogResult.Yes)
// {
// var worksheet = package.Workbook.Worksheets.Add("测试数据报表");
// // 设置默认样式
// worksheet.Cells.Style.Font.Name = "微软雅黑";
// worksheet.Cells.Style.Font.Size = 11;
// int currentRow = 1;
// // 主标题
// worksheet.Cells[currentRow, 1, currentRow, 9].Merge = true;
// var titleCell = worksheet.Cells[currentRow, 1];
// titleCell.Value = "测试数据报表";
// titleCell.Style.Font.Size = 16;
// titleCell.Style.Font.Bold = true;
// titleCell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
// titleCell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
// currentRow++;
// // 副标题
// worksheet.Cells[currentRow, 1, currentRow, 9].Merge = true;
// var subTitleCell = worksheet.Cells[currentRow, 1];
// subTitleCell.Value = $"生成时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss} | 记录数量:{CurrentReport.Count}条";
// subTitleCell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
// subTitleCell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
// currentRow += 2;
// // 表头
// string[] headers = { "编号", "联络单号", "件号", "刻字号", "数量", "初始压力(PSI)", "开始时间", "结束时间", "结束压力(PSI)", "保压时间(h)", "压差(PSI)", "温度模式", "温度", "标准差值(PSI)", "测试结果", "时间日期" };
// for (int i = 0; i < headers.Length; i++)
// {
// var cell = worksheet.Cells[currentRow, i + 1];
// cell.Value = headers[i];
// cell.Style.Font.Bold = true;
// cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
// cell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
// cell.Style.Fill.PatternType = ExcelFillStyle.Solid;
// cell.Style.Fill.BackgroundColor.SetColor(Color.LightSkyBlue);
// cell.Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black);
// // 设置列宽
// worksheet.Column(i + 1).Width = 15;
// }
// // 设置表头行高
// worksheet.Row(currentRow).Height = 35;
// currentRow++;
// // 数据行
// foreach (var data in CurrentReport)
// {
// string tempMode = GetTemperatureModeDisplay(data.Type);
// worksheet.Cells[currentRow, 1].Value = data.Id;
// worksheet.Cells[currentRow, 2].Value = data.lldh ?? "";
// worksheet.Cells[currentRow, 3].Value = data.jh ?? "";
// worksheet.Cells[currentRow, 4].Value = data.kzh ?? "";
// worksheet.Cells[currentRow, 5].Value = data.quantity;
// worksheet.Cells[currentRow, 6].Value = data.startpressure;
// CurrentReport.Clear();
// dataGridView.DataSource = new List<ConductivityTestData>();
// _repository.DeleteTestAllItems();
// worksheet.Cells[currentRow, 7].Value = data.starttime;
// worksheet.Cells[currentRow, 8].Value = data.endtime;
// worksheet.Cells[currentRow, 9].Value = data.endpressure;
// worksheet.Cells[currentRow, 10].Value = data.dwelltime;
// worksheet.Cells[currentRow, 11].Value = data.diffpressure;
// worksheet.Cells[currentRow, 12].Value = tempMode;
// worksheet.Cells[currentRow, 13].Value = data.temperature;
// worksheet.Cells[currentRow, 14].Value = data.standarderror;
// worksheet.Cells[currentRow, 15].Value = data.testresult;
// worksheet.Cells[currentRow, 16].Value = data.CreateTime;
// // 设置数据行样式
// for (int col = 1; col <= 9; col++)
// {
// var cell = worksheet.Cells[currentRow, col];
// cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
// cell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
// cell.Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.LightGray);
// // 隔行变色
// if (currentRow % 2 == 0)
// {
// cell.Style.Fill.PatternType = ExcelFillStyle.Solid;
// cell.Style.Fill.BackgroundColor.SetColor(Color.AliceBlue);
// }
// }
// // 设置格式
// worksheet.Cells[currentRow, 4].Style.Numberformat.Format = "yyyy-mm-dd hh:mm:ss";
// worksheet.Cells[currentRow, 5].Style.Numberformat.Format = "0.00";
// worksheet.Cells[currentRow, 6].Style.Numberformat.Format = "0.00";
// worksheet.Cells[currentRow, 7].Style.Numberformat.Format = "0.00";
// worksheet.Cells[currentRow, 8].Style.Numberformat.Format = "0.0";
// // 设置行高
// worksheet.Row(currentRow).Height = 25;
// currentRow++;
// }
// // 自动调整列宽
// worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
// // 保存
// package.SaveAs(new FileInfo(filePath));
// // 刷新显示
// dataGridView.Refresh();
// }
//}
private void ExportToExcel(string filePath)
private void BtnDelete_Click(object sender, EventArgs e)
{
// 获取选中的行
var selectedRows = dataGridView.Rows.Cast<DataGridViewRow>()
.Where(row => row.Cells["SelectColumn"].Value != null && (bool)row.Cells["SelectColumn"].Value)
.ToList();
if (selectedRows.Count == 0)
{
MessageBox.Show("请至少选择一行数据!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
DialogResult ask = MessageBox.Show($"确定要删除选中的 {selectedRows.Count} 条数据吗?",
"确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (ask == DialogResult.Yes)
{
try
{
// 收集要删除的ID
List<int> idsToDelete = new List<int>();
foreach (var row in selectedRows)
{
var data = row.DataBoundItem as ConductivityTestData;
if (data != null && data.Id > 0)
{
idsToDelete.Add(data.Id);
}
}
// 调用仓储删除方法(假设有一个批量删除的方法)
// 如果只有单个删除,则循环调用
foreach (int id in idsToDelete)
{
_repository.DeleteTestAllItems(id); // 需要在 Repository 中实现此方法
}
// 从内存数据源中移除被删除的对象
CurrentReport.RemoveAll(d => idsToDelete.Contains(d.Id));
// 重新绑定数据源(或直接刷新显示)
dataGridView.DataSource = null;
dataGridView.DataSource = CurrentReport;
// 刷新序号Id 列显示行号)
for (int i = 0; i < CurrentReport.Count; i++)
{
CurrentReport[i].row = i + 1;
}
dataGridView.Refresh();
MessageBox.Show($"已删除 {selectedRows.Count} 条数据。", "操作完成",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"删除失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
///// <summary>
///// 导出报表功能
///// </summary>
//private void ExportReport()
//{
// //if (CurrentReport == null || CurrentReport.Count == 0)
// //{
// // MessageBox.Show("没有数据可以导出", "提示",
// // MessageBoxButtons.OK, MessageBoxIcon.Information);
// // return;
// //}
// try
// {
// SaveFileDialog saveFileDialog = new SaveFileDialog();
// saveFileDialog.Filter = "CSV文件|*.csv|Excel文件|*.xlsx|文本文件|*.txt";
// saveFileDialog.Title = "导出报表";
// saveFileDialog.FileName = $"测试报表_{DateTime.Now:yyyyMMdd_HHmmss}";
// if (saveFileDialog.ShowDialog() == DialogResult.OK)
// {
// string filePath = saveFileDialog.FileName;
// //switch (Path.GetExtension(filePath).ToLower())
// //{
// //case ".csv":
// // ExportToCsv(filePath);
// // break;
// //case ".txt":
// // ExportToTxt(filePath);
// // break;
// //case ".xlsx":
// ExportToExcel(filePath);
// // break;
// // default:
// // ExportToCsv(filePath);
// // break;
// //}
// MessageBox.Show($"报表已成功导出到:\n{filePath}", "导出成功",
// MessageBoxButtons.OK, MessageBoxIcon.Information);
// }
// }
// catch (Exception ex)
// {
// MessageBox.Show($"导出报表失败:{ex.Message}", "错误",
// MessageBoxButtons.OK, MessageBoxIcon.Error);
// }
//}
private void ExportToExcel(string filePath, List<ConductivityTestData> dataList)
{
using (var package = new ExcelPackage())
{
@@ -927,7 +897,7 @@ namespace 全自动水压检测仪
// 副标题
worksheet.Cells[currentRow, 1, currentRow, 16].Merge = true;
var subTitleCell = worksheet.Cells[currentRow, 1];
subTitleCell.Value = $"生成时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss} | 记录数量:{CurrentReport.Count}条";
subTitleCell.Value = $"生成时间:{DateTime.Now:yyyy-MM-dd HH:mm:ss} | 记录数量:{dataList.Count}条";
subTitleCell.Style.Font.Size = 11;
subTitleCell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
subTitleCell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
@@ -981,7 +951,7 @@ namespace 全自动水压检测仪
currentRow++;
// 数据行
foreach (var data in CurrentReport)
foreach (var data in dataList)
{
string tempMode = GetTemperatureModeDisplay(data.Type);
@@ -1111,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;
}
}
}
}

View File

@@ -18,8 +18,14 @@ namespace 全自动水压检测仪
private ConductivityRepository _repository;
public ScanImport()
: this(null)
{
}
public ScanImport(NormalTemperatureMode normalTemperatureMode)
{
InitializeComponent();
_normalTemperatureMode = normalTemperatureMode;
_repository = new ConductivityRepository();
uiDataGridView1.AutoGenerateColumns = false;
}
@@ -419,17 +425,13 @@ namespace 全自动水压检测仪
}
}
}
private void SwitchWindow<T>(T windowInstance, Func<T> createFunc) where T : UIForm
private void SwitchWindow<T>(ref T windowInstance, Func<T> createFunc) where T : UIForm
{
// 需要将 windowInstance 声明为局部变量
T localInstance = windowInstance;
// 复用窗口实例
if (localInstance == null || localInstance.IsDisposed)
if (windowInstance == null || windowInstance.IsDisposed)
{
localInstance = createFunc();
localInstance.FormClosed += (s, e) =>
windowInstance = createFunc();
windowInstance.FormClosed += (s, e) =>
{
SafeInvoke(() =>
{
@@ -438,24 +440,32 @@ namespace 全自动水压检测仪
});
};
}
else
{
SafeInvoke(() => localInstance.Activate());
return;
}
T targetWindow = windowInstance;
SafeInvoke(() =>
{
this.Hide();
localInstance.Show();
if (!targetWindow.Visible)
{
targetWindow.Show();
}
targetWindow.Activate();
});
// 如果需要更新外部引用,可以返回实例
// return localInstance;
}
private void uiButton1_Click(object sender, EventArgs e)
{
SwitchWindow(_normalTemperatureMode, () => new NormalTemperatureMode());
if (_normalTemperatureMode != null && !_normalTemperatureMode.IsDisposed)
{
SafeInvoke(() =>
{
this.Hide();
_normalTemperatureMode.ResumeAfterChildWindow();
});
return;
}
SwitchWindow(ref _normalTemperatureMode, () => new NormalTemperatureMode());
}

View File

@@ -146,6 +146,7 @@
<Compile Include="CommonDefs.cs" />
<Compile Include="DATA\BoolSign.cs" />
<Compile Include="DATA\ConductividyClass.cs" />
<Compile Include="DATA\DatabaseConnectionManager.cs" />
<Compile Include="DATA\DatabaseInitializer.cs" />
<Compile Include="DATA\DataChange.cs" />
<Compile Include="DATA\FormManager.cs" />
@@ -292,4 +293,4 @@
</PropertyGroup>
<Error Condition="!Exists('..\packages\Microsoft.NETFramework.ReferenceAssemblies.net472.1.0.2\build\Microsoft.NETFramework.ReferenceAssemblies.net472.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.NETFramework.ReferenceAssemblies.net472.1.0.2\build\Microsoft.NETFramework.ReferenceAssemblies.net472.targets'))" />
</Target>
</Project>
</Project>