When I try to add a second Item to my ListView, the SubItems of the first Item are gone. The problem is very likely that you have Sorting turned on while loading the ListView.
If you have the Sorting property of your ListView set to anything except None, while you are loading the ListView, it can really cause you to think bad things, if you have not used a neat trick to load the ListView.
I was stepping through the loading of a ListView and after the first Item and its SubItems had been added, everything was correct in the ListView. However, as soon as I added the second Item (row) to the ListView, the SubItems of the first row were gone. Since I had turned on Sorting in the Designer, I didn't even remember that Sorting was turned on. After many frustrating minutes, I decided to compare the properties of two ListViews, one of which was working, and discovered that Sorting was turned on in the one that was not working. When I turned Sorting off, until the ListView was loaded, and then turned Sorting on, everything was fine.
That is one way to solve the problem of loading a Sorted ListView, but there is another and neater way to do it. I have written some code simulating the way that I was messing up the ListView so that you can see how it differs from a better and less frustrating way to get the ListView loaded with Sorting turned on. The code shown below demonstrates the way that will not work and Figure 1 shows the result in the ListView. The label at the top of the form shows the number of SubItems in Item(0) has been set to 0 instead of 3.
| Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click With Me.ListView1 .Sorting = SortOrder.Ascending .Items.Add("C Item1") .Items(0).SubItems.Add("Col 2C1") .Items(0).SubItems.Add("Col 3C1") ' add second row which will sort up and create havoc ' in the listview .Items.Add("B Item2") .Items(1).SubItems.Add("Col 2B2") .Items(1).SubItems.Add("Col 3B2") .Items.Add("A Item3") .Items(1).SubItems.Add("Col 2A3") .Items(1).SubItems.Add("Col 3A3") End With End Sub |

| Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Dim lvi As ListViewItem With Me.ListView1 .Items.Clear() .Sorting = SortOrder.Ascending lvi = .Items.Add("C Item1") lvi.SubItems.Add("Col 2C1") lvi.SubItems.Add("Col 3C1") ' add second row which will sort up lvi = .Items.Add("B Item2") lvi.SubItems.Add("Col 2B2") lvi.SubItems.Add("Col 3B2") lvi = .Items.Add("A Item3") lvi.SubItems.Add("Col 2A3") lvi.SubItems.Add("Col 3A3") Me.Label1.Text = "ListItem(0).SubItems: " & .Items(0).SubItems.Count End With End Sub |
