I've always found ListViews quite fascinating. Slightly confusing sometimes, but fascinating nevertheless.
As I have often been heard to say, it's the little Gotchas that'll get ya. Take, for instance, the subject of this blog - copying an item between ListViews. The scenario is that you let the user click on an item in ListView1 and if they want this item copied to ListView2, they hit a button.
Now, you would probably think that all you need to do is identify the currently selected item and add it straight to the second ListView. Something like:
Code Copy
ListView2.Items.Add(ListView1.SelectedItems(0))
But if you do try this, you will get an error.

The text of the error message pretty much says it all. What you have to do (assuming that you aren't prepared to remove the item from the original ListView) is to clone it. You will then be allowed to add the clone to the second ListView.
Although the cloning isn't difficult, you do have to be aware of the need to cast the selected item to ListViewItem if you have Option Strict On. To be honest, I found this a bit strange at first. If I lift a ListViewItem from a ListView, I didn't expect to have to cast it to what it is - i.e a ListViewItem.
I'm not entirely sure why this occurs and wonder if the underlying reason for this is that the ListViewItem is stored in the SelectedItems collection of the ListView as a generic object. Anyway, Casting it back to a ListViewItem at the point where the cloning takes place, fixes this without any problem.
This code works well:
If ListView1.SelectedItems.Count > 0 Then
Dim lvi As New ListViewItem
lvi = ListView1.SelectedItems(0)
Dim lvi2 As New ListViewItem
lvi2 = CType(lvi.Clone, ListViewItem)
ListView2.Items.Add(lvi2)
End If
You'll have noticed that I built in a test to ensure that an item is currently selected. It's an easy thing to forget and is sure to bring your app to a grinding halt before long if you don't build this in.
You can see where I have cast the selected item (aka lvi) to ListViewItem in Line 5. Intriguingly, casting to ListViewItem in the third line of code, e.g.
Code Copy
lvi = CType(ListView1.SelectedItems(0), ListViewItem)
doesn't cut it.