C#串行端口-并非所有数据都添加到Listview中

本文关键字:添加 Listview 数据 串行端口 | 更新日期: 2023-09-27 18:26:30

所以我将数据从Arduino传输到C#Winform,后者将数据输出到文本框并保存到文件中。传输数据的格式如下18|25|999|100~;第一部分是以秒为单位的时间,它让我知道何时跳过了一行(Arduino每秒运行一个计数器),"~"字符表示行结束。此数据被拆分为一个数组(由"|"拆分),然后将此数组添加到Listview中。

文本框中的数据是完美的,所有数据都被写入,没有一行被跳过,但随后我将数据添加到列表视图中,一些行被跳过。

  private void tData_TextChanged(object sender, EventArgs e)
    {
        if (logdata.Checked)
        {
            string output = tData.Text;
            string[] lines = output.Split(''n', ''r');
            string last_line = lines[lines.Length - 1];
            if (last_line.Contains("~"))
            {
                string output1 = tData.Text;
                string[] lines1 = output1.Split(''n', ''r');
                string last_line1 = lines1[lines.Length - 1];
                string[] splitdata = last_line1.Split('|');

                    //side task - not important
                    int time = Convert.ToInt32(Convert.ToString(splitdata[0]));
                    TimeSpan currenttime = TimeSpan.FromSeconds(time);

                    string str = currenttime.ToString(@"hh':mm':ss':fff");
                    label2.Text = str;

                    //save to file
                    string path = "database.can";
                    using (StreamWriter sw = File.AppendText(path))
                    {
                        sw.WriteLine(last_line1);
                    }
                    //check if line exists to prevent doubles 
                    ListViewItem item = listView1.FindItemWithText(splitdata[0]);
                    if (item != null)
                    {
                    // it exists
                    }
                    else
                    {
                    //doesn't exist so add it
                    var listViewItem = new ListViewItem(splitdata);
                    listView1.Items.Add(listViewItem);
                    }

                }


            }
        }

tData是写入所有数据的文本框。如果有人能帮我防止台词被跳过,我将不胜感激,过去几天我一直在为此烦恼。非常感谢。Gabe

C#串行端口-并非所有数据都添加到Listview中

所以我终于发现(多亏了@hanspasant)使用Readline()解决了这个问题,在每次读取所有字节之前,这导致一些行被跳过