str == null str.length == 0 "".equals(str)

本文探讨了在Java中如何安全地检查字符串是否为null或空,并提供了避免NullPointerException的建议。通过合理的代码实现,可以有效地处理字符串为空或null的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

str == null          //判断引用是否指向任何对象
str.length == 0  //判断引用指向的对象是否为空字符串,即字符串长度为0
"".equals(str)    //判断引用指向的对象是否为空字符串和str.length()==0效果是一样的。


但str是null时,str.equals("")和str.length==0将抛java.lang.NullPointerException异常。

                     因为equals是对象的方法

所以最好使用    "".equals(str)形式
"".equals(null)   //false

 

str==null || str.length()==0 两个一起写可以避免str=null时,抛异常。

但最好还是写成:

                       str != null && !"".equals(str)
                       str ==null  ||   "".equals(str)

 

 

 

winform中以下代码可以帮我整合成一个类供给主程序调用。目前只支持5个串口和5个modubusRTU主站的通讯读写后续可能还要增加多个这种设备。using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using EasyModbus; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button; namespace 多个串口类 { public partial class Form1 : Form { static ModbusClient modbusrtu0 = new ModbusClient("COM1"); static ModbusClient modbusrtu1 = new ModbusClient("COM2"); static ModbusClient modbusrtu2 = new ModbusClient("COM3"); static ModbusClient modbusrtu3 = new ModbusClient("COM4"); static ModbusClient modbusrtu4 = new ModbusClient("COM5"); static ModbusClient modbusrtu5 = new ModbusClient("COM6"); static ModbusClient modbusrtu6 = new ModbusClient("COM7"); static ModbusClient modbusrtu7 = new ModbusClient("COM8"); static ModbusClient modbusrtu8 = new ModbusClient("COM9"); static ModbusClient modbusrtu9 = new ModbusClient("COM10"); private Thread modbusThread0; private Thread modbusThread1; private Thread modbusThread2; private Thread modbusThread3; private Thread modbusThread4; private Thread modbusThread5; private Thread modbusThread6; private Thread modbusThread7; private Thread modbusThread8; private Thread modbusThread9; int[] modbusRtuInt_0=new int[1000]; int[] modbusRtuInt_1 = new int[1000]; int[] modbusRtuInt_2 = new int[1000]; int[] modbusRtuInt_3 = new int[1000]; int[] modbusRtuInt_4 = new int[1000]; SerialPort sPort_0; SerialPort sPort_1; SerialPort sPort_2; SerialPort sPort_3; SerialPort sPort_4; SerialPort sPort_5; SerialPort sPort_6; SerialPort sPort_7; SerialPort sPort_8; SerialPort sPort_9; private StringBuilder receivedDataBuffer0 = new StringBuilder(); private StringBuilder receivedDataBuffer1 = new StringBuilder(); private StringBuilder receivedDataBuffer2 = new StringBuilder(); private StringBuilder receivedDataBuffer3 = new StringBuilder(); private StringBuilder receivedDataBuffer4 = new StringBuilder(); string sPort0_ReceiveStr = ""; string sPort1_ReceiveStr = ""; string sPort2_ReceiveStr = ""; string sPort3_ReceiveStr = ""; string sPort4_ReceiveStr = ""; // 获取执行程序的根目录路径 public static string rootPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory); public Form1() { InitializeComponent(); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { //新建任务流程csv文件 string TaskCSVname = rootPath + "\\" + "串口数据列表.csv"; if (!File.Exists(TaskCSVname)) { try { using (FileStream fs = File.Create(TaskCSVname)) { } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show($"创建用户程序 任务流程csv文件时发生错误: {ex.Message}"); } } if (File.Exists(TaskCSVname)) { SaveDataGridViewToCsv(TaskCSVname, dataGridView); } } private void Form1_Load(object sender, EventArgs e) { DataGridViewComboBoxColumn comboBoxColumn_COM = dataGridView.Columns[2] as DataGridViewComboBoxColumn; DataGridViewComboBoxColumn comboBoxColumn_Baudrate = dataGridView.Columns[3] as DataGridViewComboBoxColumn; DataGridViewComboBoxColumn comboBoxColumn_Databits = dataGridView.Columns[4] as DataGridViewComboBoxColumn; DataGridViewComboBoxColumn comboBoxColumn_Stopbit = dataGridView.Columns[5] as DataGridViewComboBoxColumn; DataGridViewComboBoxColumn comboBoxColumn_Checkbit = dataGridView.Columns[6] as DataGridViewComboBoxColumn; DataGridViewComboBoxColumn comboBoxColumn_End = dataGridView.Columns[7] as DataGridViewComboBoxColumn; DataGridViewComboBoxColumn comboBoxColumn_Agreement = dataGridView.Columns[8] as DataGridViewComboBoxColumn; string[] portNames = SerialPort.GetPortNames(); // 获取所有可用串口的名字[^3] string[] Baudrate_strs = { "9600", "19200", "38400", "56000", "115200" }; string[] Databits_strs = { "7", "8" }; string[] Stopbit_strs = { "1","2" }; string[] Checkbit_strs = { "无校验","奇校验", "偶校验" }; string[] End_strs = { "无", "/r", "/n", "/r/n" }; string[] Agreement_strs = { "通用", "Modbus_RTU" }; foreach (string portName in portNames) { comboBoxColumn_COM.Items.Add(portName); } foreach (string Baudrate_str in Baudrate_strs) { comboBoxColumn_Baudrate.Items.Add(Baudrate_str); } foreach (string Databits_str in Databits_strs) { comboBoxColumn_Databits.Items.Add(Databits_str); } foreach (string Stopbit_str in Stopbit_strs) { comboBoxColumn_Stopbit.Items.Add(Stopbit_str); } foreach (string Checkbit_str in Checkbit_strs) { comboBoxColumn_Checkbit.Items.Add(Checkbit_str); } foreach (string End_str in End_strs) { comboBoxColumn_End.Items.Add(End_str); } foreach (string Agreement_str in Agreement_strs) { comboBoxColumn_Agreement.Items.Add(Agreement_str); } string UserProTaskCSVname = rootPath + "\\" + "串口数据列表.csv"; //读取用户程序 任务流程csv文件 if (File.Exists(UserProTaskCSVname)) { LoadCsvToFixedDataGridView(UserProTaskCSVname, dataGridView); } else { } } private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e) { string open_state = ""; string close_state = ""; // 获取点击的行索引和列索引 int rowIndex = e.RowIndex; int columnIndex = e.ColumnIndex; // 判断是否为按钮列 if (dataGridView.Columns[columnIndex] is DataGridViewButtonColumn && rowIndex >= 0) { string dgvPortName_str = dataGridView.Rows[rowIndex].Cells[2].FormattedValue.ToString(); string dgvBaudrate_str= dataGridView.Rows[rowIndex].Cells[3].FormattedValue.ToString(); string dgvDatabits_str = dataGridView.Rows[rowIndex].Cells[4].FormattedValue.ToString(); string dgvStopbit_str = dataGridView.Rows[rowIndex].Cells[5].FormattedValue.ToString(); string dgvCheckbit_str = dataGridView.Rows[rowIndex].Cells[6].FormattedValue.ToString(); string dgvAgreement_str= dataGridView.Rows[rowIndex].Cells[8].FormattedValue.ToString(); //打开连接按钮 if (columnIndex == 10) { if (rowIndex == 0) { if (dgvAgreement_str == "通用") { sPort_0 = new SerialPort(); sPort_open(sPort_0, dgvPortName_str, dgvBaudrate_str, dgvDatabits_str, dgvStopbit_str, dgvCheckbit_str, rowIndex, out open_state); } else if (dgvAgreement_str == "Modbus_RTU") { try { modbusrtu0 = new ModbusClient(dgvPortName_str); modbusrtu0.UnitIdentifier = 1; modbusrtu0.Baudrate = int.Parse(dgvBaudrate_str); // 获取选择的波特率 modbusrtu0.StopBits = StopBits.One; modbusrtu0.ConnectionTimeout = 500; //校验位 if (dgvCheckbit_str == "无") { modbusrtu0.Parity = Parity.None; } else if (dgvCheckbit_str == "奇校验") { modbusrtu0.Parity = Parity.Odd; } else if (dgvCheckbit_str == "偶校验") { modbusrtu0.Parity = Parity.Even; } // 尝试连接 modbusrtu0.Connect(); if (modbusrtu0.Connected) { open_state = "OK"; } } catch { open_state = "NG"; } if (open_state == "OK") { modbusThread0 = new Thread(ContBackgWork_modbusrtu0); modbusThread0.IsBackground = true; modbusThread0.Start(); } } if (open_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = true; } } else if (rowIndex == 1) { if (dgvAgreement_str == "通用") { sPort_1 = new SerialPort(); sPort_open(sPort_1, dgvPortName_str, dgvBaudrate_str, dgvDatabits_str, dgvStopbit_str, dgvCheckbit_str, rowIndex, out open_state); } else if (dgvAgreement_str == "Modbus_RTU") { try { modbusrtu1 = new ModbusClient(dgvPortName_str); modbusrtu1.UnitIdentifier = 1; modbusrtu1.Baudrate = int.Parse(dgvBaudrate_str); // 获取选择的波特率 modbusrtu1.StopBits = StopBits.One; modbusrtu1.ConnectionTimeout = 500; //校验位 if (dgvCheckbit_str == "无") { modbusrtu1.Parity = Parity.None; } else if (dgvCheckbit_str == "奇校验") { modbusrtu1.Parity = Parity.Odd; } else if (dgvCheckbit_str == "偶校验") { modbusrtu1.Parity = Parity.Even; } // 尝试连接 modbusrtu1.Connect(); if (modbusrtu1.Connected) { open_state = "OK"; } } catch { open_state = "NG"; } if (open_state == "OK") { modbusThread1 = new Thread(ContBackgWork_modbusrtu1); modbusThread1.IsBackground = true; modbusThread1.Start(); } } if (open_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = true; } } else if (rowIndex == 2) { if (dgvAgreement_str == "通用") { sPort_2 = new SerialPort(); sPort_open(sPort_2, dgvPortName_str, dgvBaudrate_str, dgvDatabits_str, dgvStopbit_str, dgvCheckbit_str, rowIndex, out open_state); } else if (dgvAgreement_str == "Modbus_RTU") { try { modbusrtu2 = new ModbusClient(dgvPortName_str); modbusrtu2.UnitIdentifier = 1; modbusrtu2.Baudrate = int.Parse(dgvBaudrate_str); // 获取选择的波特率 modbusrtu2.StopBits = StopBits.One; modbusrtu2.ConnectionTimeout = 500; //校验位 if (dgvCheckbit_str == "无") { modbusrtu2.Parity = Parity.None; } else if (dgvCheckbit_str == "奇校验") { modbusrtu2.Parity = Parity.Odd; } else if (dgvCheckbit_str == "偶校验") { modbusrtu2.Parity = Parity.Even; } // 尝试连接 modbusrtu2.Connect(); if (modbusrtu2.Connected) { open_state = "OK"; } } catch { open_state = "NG"; } if (open_state == "OK") { modbusThread2 = new Thread(ContBackgWork_modbusrtu2); modbusThread2.IsBackground = true; modbusThread2.Start(); } } if (open_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = true; } } else if (rowIndex == 3) { if (dgvAgreement_str == "通用") { sPort_3 = new SerialPort(); sPort_open(sPort_3, dgvPortName_str, dgvBaudrate_str, dgvDatabits_str, dgvStopbit_str, dgvCheckbit_str, rowIndex, out open_state); } else if (dgvAgreement_str == "Modbus_RTU") { try { modbusrtu3 = new ModbusClient(dgvPortName_str); modbusrtu3.UnitIdentifier = 1; modbusrtu3.Baudrate = int.Parse(dgvBaudrate_str); // 获取选择的波特率 modbusrtu3.StopBits = StopBits.One; modbusrtu3.ConnectionTimeout = 500; //校验位 if (dgvCheckbit_str == "无") { modbusrtu3.Parity = Parity.None; } else if (dgvCheckbit_str == "奇校验") { modbusrtu3.Parity = Parity.Odd; } else if (dgvCheckbit_str == "偶校验") { modbusrtu3.Parity = Parity.Even; } // 尝试连接 modbusrtu3.Connect(); if (modbusrtu3.Connected) { open_state = "OK"; } } catch { open_state = "NG"; } if (open_state == "OK") { modbusThread3 = new Thread(ContBackgWork_modbusrtu3); modbusThread3.IsBackground = true; modbusThread3.Start(); } } if (open_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = true; } } else if (rowIndex == 4) { if (dgvAgreement_str == "通用") { sPort_4 = new SerialPort(); sPort_open(sPort_4, dgvPortName_str, dgvBaudrate_str, dgvDatabits_str, dgvStopbit_str, dgvCheckbit_str, rowIndex, out open_state); } else if (dgvAgreement_str == "Modbus_RTU") { try { modbusrtu4 = new ModbusClient(dgvPortName_str); modbusrtu4.UnitIdentifier = 1; modbusrtu4.Baudrate = int.Parse(dgvBaudrate_str); // 获取选择的波特率 modbusrtu4.StopBits = StopBits.One; modbusrtu4.ConnectionTimeout = 500; //校验位 if (dgvCheckbit_str == "无") { modbusrtu4.Parity = Parity.None; } else if (dgvCheckbit_str == "奇校验") { modbusrtu4.Parity = Parity.Odd; } else if (dgvCheckbit_str == "偶校验") { modbusrtu4.Parity = Parity.Even; } // 尝试连接 modbusrtu4.Connect(); if (modbusrtu4.Connected) { open_state = "OK"; } } catch { open_state = "NG"; } if (open_state == "OK") { modbusThread4 = new Thread(ContBackgWork_modbusrtu4); modbusThread4.IsBackground = true; modbusThread4.Start(); } } if (open_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = true; } } } //关闭连接按钮 else if (columnIndex == 11) { if (rowIndex == 0) { if (dgvAgreement_str == "通用") { sPort_close(sPort_0, out close_state); } else if(dgvAgreement_str == "Modbus_RTU") { modbusThread0.Abort(); modbusrtu0.Disconnect(); close_state= "OK"; } if (close_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = false; } } else if (rowIndex == 1) { if (dgvAgreement_str == "通用") { sPort_close(sPort_1, out close_state); } else if (dgvAgreement_str == "Modbus_RTU") { modbusThread1.Abort(); modbusrtu1.Disconnect(); close_state = "OK"; } if (close_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = false; } } else if (rowIndex == 2) { if (dgvAgreement_str == "通用") { sPort_close(sPort_2, out close_state); } else if (dgvAgreement_str == "Modbus_RTU") { modbusThread2.Abort(); modbusrtu2.Disconnect(); close_state = "OK"; } if (close_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = false; } } else if (rowIndex == 3) { if (dgvAgreement_str == "通用") { sPort_close(sPort_3, out close_state); } else if (dgvAgreement_str == "Modbus_RTU") { modbusThread3.Abort(); modbusrtu3.Disconnect(); close_state = "OK"; } if (close_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = false; } } else if (rowIndex == 4) { if (dgvAgreement_str == "通用") { sPort_close(sPort_4, out close_state); } else if (dgvAgreement_str == "Modbus_RTU") { modbusThread4.Abort(); modbusrtu4.Disconnect(); close_state = "OK"; } if (close_state == "OK") { dataGridView.Rows[rowIndex].Cells[9].Value = false; } } } } } private void sPort_open(SerialPort sPort, string PortName, string Baudrate, string Databits, string Stopbit, string Checkbit,int Row,out string Result) { Result = ""; if (sPort.IsOpen == false) { try { sPort.PortName = PortName; // 获取选择的串口端口 sPort.BaudRate = int.Parse(Baudrate); // 获取选择的波特率 sPort.DataBits = int.Parse(Databits); // 数据位 //停止位 if (Stopbit == "1") { sPort.StopBits = StopBits.One; } else if (Stopbit == "2") { sPort.StopBits = StopBits.Two; } //校验位 if (Checkbit == "无校验") { sPort.Parity = Parity.None; } else if (Checkbit == "奇校验") { sPort.Parity = Parity.Odd; } else if (Checkbit == "偶校验") { sPort.Parity = Parity.Even; } // 打开串口 sPort.Open(); if (sPort.IsOpen) { if (Row == 0) { sPort.DataReceived += sPort0_DataReceived; } else if (Row == 1) { sPort.DataReceived += sPort1_DataReceived; } else if (Row == 2) { sPort.DataReceived += sPort2_DataReceived; } else if (Row == 3) { sPort.DataReceived += sPort3_DataReceived; } else if (Row == 4) { sPort.DataReceived += sPort4_DataReceived; } Result = "OK"; } } catch { Result = "NG"; } } else { Result = "opened"; } } private void sPort_close(SerialPort sPort, out string Result) { if (sPort != null && sPort.IsOpen) { sPort.Close(); Result = "OK"; } else { Result = "closed"; } } private void button1_Click(object sender, EventArgs e) { if (comboBox1.SelectedIndex == 0) { sPort_send(sPort_0, textBox1.Text); } else if (comboBox1.SelectedIndex == 1) { sPort_send(sPort_1, textBox1.Text); } else if (comboBox1.SelectedIndex == 2) { sPort_send(sPort_2, textBox1.Text); } } private void sPort_send(SerialPort sPort,string sendData) { if (sPort != null && sPort.IsOpen) { try { // 转换为字节数组并通过串口发送 byte[] buffer = Encoding.UTF8.GetBytes(sendData); sPort.Write(buffer, 0, buffer.Length); } catch (Exception ex) { MessageBox.Show("COM发送数据失败!"); } } } private void sPort0_DataReceived(object sender, SerialDataReceivedEventArgs e) { string end_str=dataGridView.Rows[0].Cells[7].FormattedValue.ToString(); // 创建临时存储空间保存本次读取的结果 byte[] buffer = new byte[sPort_0.BytesToRead]; int bytesReadCount = sPort_0.Read(buffer, 0, buffer.Length); // 追加新获取的内容至全局累积变量中 string newDataString = Encoding.UTF8.GetString(buffer, 0, bytesReadCount); receivedDataBuffer0.Append(newDataString); if (end_str == "/r" || end_str == "/n" || end_str == "/r/n") { int endIndex = 0; if (end_str == "/r") { endIndex = receivedDataBuffer0.ToString().LastIndexOf("\r"); } else if (end_str == "/n") { endIndex = receivedDataBuffer0.ToString().LastIndexOf("\n"); } else if (end_str == "/r/n") { endIndex = receivedDataBuffer0.ToString().LastIndexOf("\r\n"); } if (endIndex > 0) { // 提取消息主体部分 string completeMessage = receivedDataBuffer0.ToString(0, endIndex).Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer0.Remove(0, receivedDataBuffer0.Length); // 输出处理后的结果 sPort0_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } else if (end_str == "" || end_str == "无") { Thread.Sleep(100); // 提取消息主体部分 string completeMessage = receivedDataBuffer0.ToString().Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer0.Remove(0, receivedDataBuffer0.Length); // 输出处理后的结果 sPort0_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } private void sPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) { string end_str = dataGridView.Rows[1].Cells[7].FormattedValue.ToString(); // 创建临时存储空间保存本次读取的结果 byte[] buffer = new byte[sPort_1.BytesToRead]; int bytesReadCount = sPort_1.Read(buffer, 0, buffer.Length); // 追加新获取的内容至全局累积变量中 string newDataString = Encoding.UTF8.GetString(buffer, 0, bytesReadCount); receivedDataBuffer1.Append(newDataString); if (end_str == "/r" || end_str == "/n" || end_str == "/r/n") { int endIndex = 0; if (end_str == "/r") { endIndex = receivedDataBuffer1.ToString().LastIndexOf("\r"); } else if (end_str == "/n") { endIndex = receivedDataBuffer1.ToString().LastIndexOf("\n"); } else if (end_str == "/r/n") { endIndex = receivedDataBuffer1.ToString().LastIndexOf("\r\n"); } if (endIndex > 0) { // 提取消息主体部分 string completeMessage = receivedDataBuffer1.ToString(0, endIndex).Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer1.Remove(0, receivedDataBuffer1.Length); // 输出处理后的结果 sPort1_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } else if (end_str == "" || end_str == "无") { Thread.Sleep(100); // 提取消息主体部分 string completeMessage = receivedDataBuffer1.ToString().Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer1.Remove(0, receivedDataBuffer1.Length); // 输出处理后的结果 sPort1_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } private void sPort2_DataReceived(object sender, SerialDataReceivedEventArgs e) { string end_str = dataGridView.Rows[2].Cells[7].FormattedValue.ToString(); // 创建临时存储空间保存本次读取的结果 byte[] buffer = new byte[sPort_2.BytesToRead]; int bytesReadCount = sPort_2.Read(buffer, 0, buffer.Length); // 追加新获取的内容至全局累积变量中 string newDataString = Encoding.UTF8.GetString(buffer, 0, bytesReadCount); receivedDataBuffer2.Append(newDataString); if (end_str == "/r" || end_str == "/n" || end_str == "/r/n") { int endIndex = 0; if (end_str == "/r") { endIndex = receivedDataBuffer2.ToString().LastIndexOf("\r"); } else if (end_str == "/n") { endIndex = receivedDataBuffer2.ToString().LastIndexOf("\n"); } else if (end_str == "/r/n") { endIndex = receivedDataBuffer2.ToString().LastIndexOf("\r\n"); } if (endIndex > 0) { // 提取消息主体部分 string completeMessage = receivedDataBuffer2.ToString(0, endIndex).Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer2.Remove(0, receivedDataBuffer2.Length); // 输出处理后的结果 sPort2_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } else if (end_str == "" || end_str == "无") { Thread.Sleep(100); // 提取消息主体部分 string completeMessage = receivedDataBuffer2.ToString().Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer2.Remove(0, receivedDataBuffer2.Length); // 输出处理后的结果 sPort2_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } private void sPort3_DataReceived(object sender, SerialDataReceivedEventArgs e) { string end_str = dataGridView.Rows[3].Cells[7].FormattedValue.ToString(); // 创建临时存储空间保存本次读取的结果 byte[] buffer = new byte[sPort_3.BytesToRead]; int bytesReadCount = sPort_3.Read(buffer, 0, buffer.Length); // 追加新获取的内容至全局累积变量中 string newDataString = Encoding.UTF8.GetString(buffer, 0, bytesReadCount); receivedDataBuffer3.Append(newDataString); if (end_str == "/r" || end_str == "/n" || end_str == "/r/n") { int endIndex = 0; if (end_str == "/r") { endIndex = receivedDataBuffer3.ToString().LastIndexOf("\r"); } else if (end_str == "/n") { endIndex = receivedDataBuffer3.ToString().LastIndexOf("\n"); } else if (end_str == "/r/n") { endIndex = receivedDataBuffer3.ToString().LastIndexOf("\r\n"); } if (endIndex > 0) { // 提取消息主体部分 string completeMessage = receivedDataBuffer3.ToString(0, endIndex).Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer3.Remove(0, receivedDataBuffer3.Length); // 输出处理后的结果 sPort3_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } else if (end_str == "" || end_str == "无") { Thread.Sleep(100); // 提取消息主体部分 string completeMessage = receivedDataBuffer3.ToString().Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer3.Remove(0, receivedDataBuffer3.Length); // 输出处理后的结果 sPort3_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } private void sPort4_DataReceived(object sender, SerialDataReceivedEventArgs e) { string end_str = dataGridView.Rows[4].Cells[7].FormattedValue.ToString(); // 创建临时存储空间保存本次读取的结果 byte[] buffer = new byte[sPort_4.BytesToRead]; int bytesReadCount = sPort_4.Read(buffer, 0, buffer.Length); // 追加新获取的内容至全局累积变量中 string newDataString = Encoding.UTF8.GetString(buffer, 0, bytesReadCount); receivedDataBuffer4.Append(newDataString); if (end_str == "/r" || end_str == "/n" || end_str == "/r/n") { int endIndex = 0; if (end_str == "/r") { endIndex = receivedDataBuffer4.ToString().LastIndexOf("\r"); } else if (end_str == "/n") { endIndex = receivedDataBuffer4.ToString().LastIndexOf("\n"); } else if (end_str == "/r/n") { endIndex = receivedDataBuffer4.ToString().LastIndexOf("\r\n"); } if (endIndex > 0) { // 提取消息主体部分 string completeMessage = receivedDataBuffer4.ToString(0, endIndex).Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer4.Remove(0, receivedDataBuffer4.Length); // 输出处理后的结果 sPort4_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } else if (end_str == "" || end_str == "无") { Thread.Sleep(100); // 提取消息主体部分 string completeMessage = receivedDataBuffer4.ToString().Trim(); // 清理缓冲区保留剩余未解析的部分 receivedDataBuffer4.Remove(0, receivedDataBuffer4.Length); // 输出处理后的结果 sPort4_ReceiveStr = completeMessage; // 执行进一步业务逻辑... } } //************************************ DataGridView操作方法 ***************************************** #region DataGridView操作方法 private void SaveDataGridViewToCsv(string filePath, DataGridView dgv) { StringBuilder sb = new StringBuilder(); // 添加表头 for (int colIdx = 0; colIdx < dgv.Columns.Count; colIdx++) { sb.Append(dgv.Columns[colIdx].HeaderText); if (colIdx != dgv.Columns.Count - 1) sb.Append(","); } sb.AppendLine(); // 遍历所有行并将数据追加到字符串中 foreach (DataGridViewRow row in dgv.Rows) { for (int cellIdx = 0; cellIdx < dgv.Columns.Count; cellIdx++) { if (dgv.Columns[cellIdx] is DataGridViewComboBoxColumn comboBoxCol) { sb.Append(row.Cells[cellIdx].FormattedValue); // 获取 ComboBox 显示值 } else if (dgv.Columns[cellIdx] is DataGridViewCheckBoxColumn checkBoxCol) { sb.Append(row.Cells[cellIdx].EditedFormattedValue.ToString()); // 获取 CheckBox 勾选状态 } else { sb.Append(row.Cells[cellIdx].Value?.ToString() ?? ""); // 普通文本列 } if (cellIdx != dgv.Columns.Count - 1) sb.Append(","); } sb.AppendLine(); } // 写入文件 System.IO.File.WriteAllText(filePath, sb.ToString(), Encoding.UTF8); } private void LoadCsvToFixedDataGridView(string filePath, DataGridView dgv) { dgv.Rows.Clear(); try { List<string[]> rowsData = new List<string[]>(); using (StreamReader sr = new StreamReader(filePath)) { string line; int rowIndex = 0; while ((line = sr.ReadLine()) != null) { if (rowIndex == 0) { rowIndex++; continue; } // 跳过表头 string[] rowData = line.Split(','); rowsData.Add(rowData); } } foreach (var rowData in rowsData) { object[] valuesToAdd = new object[dgv.Columns.Count]; for (int i = 0; i < dgv.Columns.Count; i++) { if (dgv.Columns[i] is DataGridViewComboBoxColumn comboBoxCol) { valuesToAdd[i] = comboBoxCol.Items.Cast<object>() .FirstOrDefault(item => item.ToString().Equals(rowData[i], StringComparison.OrdinalIgnoreCase)); } else if (dgv.Columns[i] is DataGridViewCheckBoxColumn checkBoxCol) { valuesToAdd[i] = bool.TryParse(rowData[i], out bool isChecked) ? isChecked : false; } else { valuesToAdd[i] = rowData[i]; } } dgv.Rows.Add(valuesToAdd); } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(dgv.Name.ToString() + " Failed to load data from CSV file." + Environment.NewLine + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } // 判断是否有足够的行可删 if (dgv.Rows.Count > 1) { // 获取最后一个非新行的索引 int lastIndex = dgv.Rows.Count - 2; // 移除该行 dgv.Rows.RemoveAt(lastIndex); } } #endregion private void ContBackgWork_modbusrtu0() { while (true) { try { modbusRtuInt_0 = modbusrtu0.ReadHoldingRegisters(0, 10); } catch { } Thread.Sleep(10); } } private void ContBackgWork_modbusrtu1() { while (true) { try { modbusRtuInt_1 = modbusrtu1.ReadHoldingRegisters(0, 10); } catch { } Thread.Sleep(10); } } private void ContBackgWork_modbusrtu2() { while (true) { try { modbusRtuInt_2 = modbusrtu2.ReadHoldingRegisters(0, 10); } catch { } Thread.Sleep(10); } } private void ContBackgWork_modbusrtu3() { while (true) { try { modbusRtuInt_3 = modbusrtu3.ReadHoldingRegisters(0, 10); } catch { } Thread.Sleep(10); } } private void ContBackgWork_modbusrtu4() { while (true) { try { modbusRtuInt_4 = modbusrtu4.ReadHoldingRegisters(0, 10); } catch { } Thread.Sleep(10); } } private void timer1_Tick(object sender, EventArgs e) { label1.Text = sPort0_ReceiveStr; label2.Text = sPort1_ReceiveStr; label3.Text = sPort2_ReceiveStr; }
最新发布
07-19
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值