过了一会儿,问题就出现了。我已经调试了很多次而没有找到解决方案。我对C#知之甚少,对我的项目来说是强制性的。它一直显示问题,我真的需要一个解决方案尽快。我已经在这里搜索并尝试所有可能的解决方案,但没有运气。我标记了始终显示问题的行,
int.TryParse(data2[0], out humidity);
int.TryParse(data2[1], out pH);
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using Microsoft.Office.Interop.Excel;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
private int hr, min, sec;
private int Daydate, monthdate, yeardate;
private int i, humidity=0;
private int j, pH=0;
private int t = 0;
private string data;
// private string[] data2;
private int flag;
int[] data_new = new int[6];
private void button1_Click(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "" || comboBox2.Text == "")
{
MessageBox.Show("Please select Port/Baud Rate Settings");
}
else
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.DataReceived += SerialPort1_DataReceived;
serialPort1.Open();
timer2.Enabled = true;
}
}
catch (UnauthorizedAccessException)
{
MessageBox.Show("Unauthorized Access");
}
}
private void button3_Click(object sender, EventArgs e)
{
t = 0;
Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = Excel.Workbooks.Add(XlSheetType.xlWorksheet);
Worksheet ws = (Worksheet)Excel.ActiveSheet;
Excel.Visible = true;
ws.Cells[1, 1] = "Humidity";
ws.Cells[1, 2] = "pH";
for(int j =2;j<= dataGridView1.Rows.Count + 1;j++)
{
for(int i=1;i<=2;i++)
{
ws.Cells[j, i] = dataGridView1.Rows[j-2].Cells[i-1].Value;
}
}
}
private void timer2_Tick(object sender, EventArgs e)
{
if(flag == 0)
{
serialPort1.WriteLine("N");
flag = 1;
}
}
private void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// if (t < 5)
// {
if (flag == 1)
{
data = serialPort1.ReadExisting();
flag = 0;
if(data != "")
{
this.Invoke(new EventHandler(displaydata_event));
}
}
// t++;
// }
}
private void displaydata_event(object sender, EventArgs e)
{
textBox3.Text = data;
string[] data2 = new string[2];
data2 = data.Split(new char[] { ',' });
int.TryParse(data2[0], out humidity);
int.TryParse(data2[1], out pH);
// Array.Clear(data2, 0, data2.Length);
textBox1.Text = humidity + "";
textBox2.Text = pH + "";
//if (Int32.Parse(data2[0]) > 0 && Int32.Parse(data2[1]) > 0)
if (humidity > 0 && pH > 0)
{
dataGridView1.Rows.Add();
//dataGridView1.Rows[i++].Cells[0].Value = Int32.Parse(data2[0]) + "";
//dataGridView1.Rows[j++].Cells[1].Value = Int32.Parse(data2[1]) + "";
dataGridView1.Rows[i++].Cells[0].Value = humidity + "";
dataGridView1.Rows[j++].Cells[1].Value = pH + "";
}
}
private void button2_Click(object sender, EventArgs e)
{
serialPort1.Close();
timer2.Enabled = false;
MessageBox.Show("Connection Closed");
}
private void timer1_Tick(object sender, EventArgs e)
{
hr = DateTime.Now.Hour;
DayOfWeek today = DateTime.Today.DayOfWeek;
min = DateTime.Now.Minute;
sec = DateTime.Now.Second;
Daydate = DateTime.Now.Day;
monthdate = DateTime.Now.Month;
yeardate = DateTime.Now.Year;
if (hr > 12)
hr -= 12;
label1.Text = hr + ":" + min + " ";
label2.Text = Daydate + "/" + monthdate + "/" + yeardate;
label3.Text = Convert.ToString(today);
}
public Form1()
{
InitializeComponent();
DayOfWeek today = DateTime.Today.DayOfWeek;
hr = DateTime.UtcNow.Hour;
min = DateTime.UtcNow.Minute;
sec = DateTime.UtcNow.Second;
Daydate = DateTime.UtcNow.Day;
String[] ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(ports);
}
}
}
答案 0 :(得分:0)
您需要检查以确保您对.Split()
的调用实际生成了两个值 - 如果该字符串不包含,
。
所以将代码更改为:
data2 = data.Split(new char[] { ',' });
// CHECK to make sure you get **TWO VALUES** here! If not, return
if (data2.Length < 2)
{
return; // didn't split into two parts --> something's wrong
}
// only KNOW that you've CHECKED, convert the string parts into int
int.TryParse(data2[0], out humidity);
int.TryParse(data2[1], out pH);
答案 1 :(得分:0)
错误很简单,可以看到。
textBox3.Text = data; //Get input data, example "1,2", or "1" or "1,2,3"
string[] data2 = new string[2]; //Initialize to arra with 2 spots.
data2 = data.Split(new char[] { ',' });//Over write to array with unkown amount of spots
int.TryParse(data2[0], out humidity); //Parse first
int.TryParse(data2[1], out pH); //Parse second
我感谢您通过评论查看问题,那么我们如何解决这个问题呢? 我们要做的第一件事就是测试长度,看看它是否合适。
textBox3.Text = data; //Get input data, example "1,2", or "1" or "1,2,3"
string[] data2 = data.Split(new char[] { ',' });
if(data2.length != 2){
//Tell the user or something like the field needs to contain 2 numbers.
return;
}
虽然我们可能会考虑另一个可能的问题。 TyParse因某种原因返回bool,它告诉我们是否成功。所以我们应该有这样的事情。
if(!int.TryParse(data2[0], out humidity)
&& !int.TryParse(data2[1], out pH)){
//Tell the user or something like the field needs to contain 2 numbers.
return;
}