I'm trying to implement a reorder-by-drag-and-drop feature to an ObjectListView. Consider the following class:
public class MyClass
{
public string Name { get; set; }
public MyClass(string name)
{
Name = name;
}
}
I got the reordering working (however it is very, very ugly), but I cant seem to find out how I should reorder my List<MyClass>
which is what the OLV is displaying? I tried removing the MyClass object at the position of the OLV Selected Index, and inserting at the new position, but that did not work.
In case you need it, here is the code I used to get the View Drag and Drop working:
private void objectListView1_ItemDrag(object sender, ItemDragEventArgs e)
{
DoDragDrop(((OLVListItem)e.Item).RowObject, DragDropEffects.Move);
}
private void objectListView1_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.Data.GetDataPresent("Cheeseburger.MyClass") ? DragDropEffects.Move : DragDropEffects.None;
}
private void objectListView1_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
var olv = (sender as ObjectListView);
if(e.Data.GetDataPresent("Cheeseburger.MyClass"))
{
var pt = olv.PointToClient(new Point(e.X, e.Y));
var index = olv.InsertionMark.NearestIndex(pt);
// Debugging
Text = index.ToString();
var node = olv.GetItem(index);
if (node != null && index != -1)
{
node.EnsureVisible();
}
}
}
private void objectListView1_DragDrop(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
var olv = (sender as ObjectListView);
if (e.Data.GetDataPresent("Cheeseburger.MyClass"))
{
var draggedObject = e.Data.GetData("Cheeseburger.MyClass") as MyClass;
var pt = olv.PointToClient(new Point(e.X, e.Y));
var index = olv.InsertionMark.NearestIndex(pt);
var node = olv.GetItem(index);
if (node != null && index != -1)
{
var models = new List<MyClass>() { draggedObject };
olv.MoveObjects(index + 1, models);
}
}
}
If my question lacks any info, please let me know - thank you!
Once again, when the question has been asked, the answer is obvious!
The problem was this line:
olv.MoveObjects(index + 1, models);
As I said, I tried using Insert and Remove on the List of Objects, but that didnt work - that was because I forgot to + 1
the index in the Insert
method (only if the index is not 0, else it messes up when dropping on the first item in the list)!
Here is the modified code for that section:
var selIndex = olv.SelectedIndex;
var models = new List<MyClass>() { draggedObject };
if (index != 0) index++;
olv.MoveObjects(index, models);
MyClasses.Insert(index,draggedObject);
MyClasses.RemoveAt(selIndex);