Search code examples
listviewserial-portmodem

Going wrong while adding items to list view from serial port..


I am reading the serial port to read the messages present in the gsm modem, and then displaying them in a listview. But i am ending up having a list view with redundant items. I am unable to understand why this is happening..

{
        port.DiscardOutBuffer();
        port.DiscardInBuffer();
        string res;
        Thread.Sleep(5000);
        res = port.ReadExisting();
        ShortMessageCollection messages = new ShortMessageCollection();
        Regex r = new Regex(@"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");
        Match m = r.Match(res);
        while (m.Success)
        {
            ShortMessage msg = new ShortMessage();

            msg.Index = m.Groups[1].Value;
            msg.Status = m.Groups[2].Value;
            msg.Sender = m.Groups[3].Value;
            msg.Alphabet = m.Groups[4].Value;
            msg.Sent = m.Groups[5].Value;
            msg.Message = m.Groups[6].Value;
            messages.Add(msg);
            m = m.NextMatch();
            objShortMessageCollection = (ShortMessageCollection)messages;
            foreach (ShortMessage mesg in objShortMessageCollection)
            {
                ListViewItem item = new ListViewItem(new string[] {mesg.Index, mesg.Sender, mesg.Message, mesg.Sent});
                item.Tag = mesg;
                lvwMessages.Items.Insert(0, item);
            }
         }

Solution

  • Use the following code to delete redundancies:

                lvwMessages.Sorting = SortOrder.Descending;
                int i = 0;
                while (i < lvwMessages.Items.Count - 1)
                {
                    if (lvwMessages.Items[i].Tag == lvwMessages.Items[i + 1].Tag)
                        lvwMessages.Items[i + 1].Remove();
                    else
                        i++;
                }