There are a couple of different ways.
If you want to copy the items from a to b:
private static void CopySelectedItems(ListView source, ListView target)
{
foreach (ListViewItem item in source.SelectedItems)
{
target.Items.Add((ListViewItem)item.Clone());
}
}
If you want to move the items from a to b:
private static void MoveSelectedItems(ListView source, ListView target)
{
while (source.SelectedItems.Count > 0)
{
ListViewItem temp = source.SelectedItems[0];
source.Items.Remove(temp);
target.Items.Add(temp);
}
}
Update
You mention that you want to preserve the order in which the items are located in the source ListView
control. I assume that they appear there in some sorted order? If so, you can create a function that uses the same sorting rule to figure out where to insert an item in the target ListView
(my example uses the value in the second column:
private static void CopySelectedItems(ListView source, ListView target)
{
foreach (ListViewItem item in source.SelectedItems)
{
ListViewItem clone = (ListViewItem)item.Clone();
target.Items.Insert(GetInsertPosition(clone, target), clone); ;
}
}
private static int GetInsertPosition(ListViewItem item, ListView target)
{
const int compareColumn = 1;
foreach (ListViewItem targetItem in target.Items)
{
if (targetItem.SubItems[compareColumn].Text.CompareTo(item.SubItems[compareColumn].Text) > 0)
{
return targetItem.Index;
}
}
return target.Items.Count;
}
It's hard to give a more exact answer without knowing more details.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…