Search code examples
c#listviewserial-porttextchanged

C# Serial port- Not all data added to Listview


so I am transmitting data from an Arduino to a C# Winform that outputs the data to a text box and saves it to a file. The format of the transmitted data is as follows 18|25|999|100~; the first part is the time in seconds which allows me to know when a line has been skipped(the Arduino runs a counter every second), the '~' character denotes line end. This data gets split up into an array(split by '|'), this array is then added to a Listview.

The data in the text box is perfect, all data is written, no line is skipped, but then I add the data to a listview and some lines are skipped.

  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 is the text box where all the data is written. I would greatly appreciate if someone could help me prevent lines from being skipped, I've been pulling out my hair over this for the past few days. Thank you, Gabe


Solution

  • so I finally figured out(thanks to @hanspassant) that using Readline() fixes the problem, before all the bytes were read one at a time which caused some lines to be skipped