Question

I am trying to make an application that lets me Check items in the ListView, and that all works fine, BUT if I add more items to the ListView while items are checked. It unchecks them all because the ListView is reloaded. Is there a way to get around this? So all of my items stay checked even when I add new ones to it? This is my current code.

            TextReader reader = new StringReader(richTextBox1.Text);
            string[] strItems = null;
            foreach (ListViewItem items in listView1.Items)
            {
                items.Remove();
            }
            while (reader.Peek() != -1)
            {
                ListViewItem item = new ListViewItem();
                strItems = reader.ReadLine().Split("-".ToCharArray());
                item.Text = strItems[0].ToString();
                item.SubItems.Add(strItems[1].ToString());
                item.SubItems.Add(strItems[2].ToString());
                item.SubItems.Add(strItems[3].ToString());
                item.SubItems.Add(strItems[4].ToString());
                listView1.Items.Add(item);
            }
Was it helpful?

Solution

you can do something like that (and improve it a little by finding a better tag / exist logic):

        TextReader reader = new StringReader(richTextBox1.Text);
        string[] strItems = null;
        while (reader.Peek() != -1)
        {
            string nextRow = reader.ReadLine();
            if (!listView1.Items.ContainsKey(nextRow.GetHashCode().ToString()))
            {
               ListViewItem item = new ListViewItem();
               item.Name = nextRow.GetHashCode().ToString();
               strItems = nextRow .Split("-".ToCharArray());
               item.Text = strItems[0].ToString();
               item.SubItems.Add(strItems[1].ToString());
               item.SubItems.Add(strItems[2].ToString());
               item.SubItems.Add(strItems[3].ToString());
               item.SubItems.Add(strItems[4].ToString());
               listView1.Items.Add(item);
            }
        }

The only problem with that is if you are trying to delete items that won't be in the new read strings, but you can solve it too (tell me if you need it and i will add it)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top