tags:

views:

46

answers:

1

Is there a way to copy the entire contents of a listview from one control to another, without manually setting up the second one and iterating through each item? I'm thinking something like:

ListView myNewListView = new ListView();
lvwExistingView.CopyTo(myNewListView);

Or even:

ListView myNewListView = new ListView();
lvwExistingView.Items.CopyTo(myNewListView.Items, 1); // This doesn't work because it expects an array
+5  A: 

A ListViewItem can't exist on more than one list view at one time. They need to be recreated.

But you can use LINQ to make this quick.

myNewListView.Items.AddRange(
    lvwExistingView.Items.Cast<ListViewItem>().Select(i => 
        i.Clone()).Cast<ListViewItem>().ToArray());
Codesleuth
I get the following compile error when I try this:Argument '1': cannot convert from 'object[]' to 'System.Windows.Forms.ListViewItem[]'
pm_2
Sorry, forgot the result of `Clone()` is an `object`. The change I've made should fix that (forces a `Cast` to `ListViewItem`).
Codesleuth