Alpha Alpha -3 years ago 205
C# Question

Move Listview with datatable into another listview

I want to move the selected row to the listview beside it. The source listview has FullRowSelect = true and MultiSelect = false. The source listview is populated via Data table from Database.

Listview

Here is what i have so far. It only moves the selected item. I want it to move the whole selected row.

private static void MoveSelectedItems(ListView source, ListView target)
{

for (int i = 0; i < source.Items.Count; i++)
{
if (source.Items[i].Selected)
{
target.Items.Add(source.Items[i]);

}
}
}


This is what happens when i run the code.

Output

Answer Source

Firstly, since you have set MultiSelect to false, you dont need the loop to iterate over all items.

Secondly, the moving part is just simple. You take the selected item and add that in the target items. Since your are moving, and not just copying, we will also remove the item from the source listview.

private static void MoveSelectedItems(ListView source, ListView target)
{
    if(source.SelectedItems.Count > 0)
    {
        ListViewItem selectedItem= source.SelectedItems[0];
        foreach (var subItem in source.SelectedItems[0].SubItems)
        {
             selectedItem.SubItems.Add (subItem);
        }
        source.Items.Remove(selectedItem);
        target.Items.Add(selectedItem);
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download