I'm currently writing a photo album sotware in C#.
I'm using a ListView component to diaplay thumbnail previews of the photos
and want to give the user the possibility to rearrange the photos via a
drag&drop operation. The problem is that it only appears to be possible to
rearrange items in a ListView if its view property is not set to
View.LargeIcons (which is the one I need to diaplay the thumbs). If I
rearrage the items without changing the view, the moved items are placed at
the end of the list and if I change the view to View.List before the
rearranging I can't change it back again.
Here's the code:
private void lvPhotos_DragDrop(object sender,
System.Windows.Forms.DragEventArgs e)
{
// prevent lvPhotos from redrawing itself
lvPhotos.BeginUpdate();
// get the new location of the items
Point p = lvPhotos.PointToClient(new Point(e.X, e.Y));
int destIndex = lvPhotos.GetItemAt(p.X, p.Y).Index;
// create a new ListViewItems array
ListViewItem[] selItems = new ListViewItem[lvPhotos.SelectedItems.Count];
int[] selIndices = new int[lvPhotos.SelectedIndices.Count];
// create the listViewItems array that will be used instead of the
currently displayed one
ListViewItem[] newItems = new ListViewItem[lvPhotos.Items.Count];
for(int i = 0; i < selItems.Length; i++)
{
if(lvPhotos.SelectedIndices[i] == destIndex) // if any of the
selectedIndices is equal to the destIndex abort the operation
return;
// fill the array with the currently selected items
selItems[i] = (ListViewItem)
lvPhotos.Items[lvPhotos.SelectedIndices[i]].Clone();
// add the current selectedIndex to the selIndices array
selIndices[i] = lvPhotos.SelectedIndices[i];
}
// rearrange the photos in the album and break the operation if it can't
be saved
if(DoAlbumDragDrop(selIndices, destIndex) == false)
return;
// switch the lvPhotos view to List, since we can't edit the item
arrangement in LargeIcon view
lvPhotos.View = View.List;
// add the items to lvPhotos
for(int i = selItems.Length - 1; i >= 0; i--)
lvPhotos.Items.Insert(destIndex, selItems[i]);
// remove the old items from lvPhotos
foreach(ListViewItem item in lvPhotos.SelectedItems)
lvPhotos.Items.Remove(item);
// create a temp ImageList
ImageList ilTemp = new ImageList();
// fill the temp il with the photos in rearranged order
for(int i = 0; i < ilThumbs.Images.Count; i++)
{
if(i == destIndex)
{
int j;
for(j = selIndices.Length - 1; j >= 0; j--)
ilTemp.Images.Add(ilThumbs.Images[j]);
j = 0;
for(i = i; i < ilThumbs.Images.Count; i++)
{
if(i == selIndices[j])
j++;
else
ilTemp.Images.Add(ilThumbs.Images[i + j]);
}
break;
}
ilTemp.Images.Add(ilThumbs.Images[i]);
}
// replace the current il with ilTemp
ilThumbs.Images.Clear();
for(int i = 0; i < ilTemp.Images.Count; i++)
{
ilThumbs.Images.Add(ilTemp.Images[i]);
lvPhotos.Items[i].ImageIndex = i;
}
// reset the lvPhotos view
lvPhotos.View = View.LargeIcon;
// redraw lvPhotos
lvPhotos.EndUpdate();
lvPhotos.Refresh();
}
Thanks for your help in advance! :)