Mike
Mike

Reputation: 73

C# Listview Drag and Drop Rows

I'm trying to implement a C# drag and drop row-reorder with a listview which would then update an SQL database with the current order of the rows. I've come across some snippets of code on the internet (one from this website which implemented a 'var' class) but none seem to be working with my needs. I don't need help updating the database as I have a good idea how I'd do this, but can't seem to get the row reordering to work correctly, any input would be appreciated.

-thanks

m&a

Upvotes: 7

Views: 15194

Answers (2)

Matthew Vines
Matthew Vines

Reputation: 27561

  1. Ensure that AllowDragDrop is set to true.

  2. Implement handlers for at least these 3 events

    private void myList_ItemDrag(object sender, ItemDragEventArgs e)
        {
            DoDragDrop(e.Item, DragDropEffects.Link);
        }
    
        private void myList_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Link;
        }
    
        private void myList_DragDrop(object sender, DragEventArgs e)
        {
            // do whatever you need to reorder the list.
        }
    

    Getting the index of the row you dropped onto may look something like:

    Point cp = myList.PointToClient(new Point(e.X, e.Y));
    ListViewItem dragToItem = myList.GetItemAt(cp.X, cp.Y);
    int dropIndex = dragToItem.Index;
    

Upvotes: 15

Adam Houldsworth
Adam Houldsworth

Reputation: 64467

I know this isn't ListView specific, but I have sample code for implementing row drag and drop out of / into a DataGridView. Some of it is obviously control specific, other code is actually pretty generic (such as deciding when its a drag):

http://adamhouldsworth.blogspot.com/2010/01/datagridview-multiple-row-drag-drop.html

Completely forgot the fact that ListView already allows drag-dropping!

I can also add some theory - when the drop occurs on your control, you will need to hit test on those coordinates (likely a method called HitTest) on the ListView to see what row was hit, this is the basis for where to insert the row being dragged.

Unrelated - is that var class perhaps the new var keyword in C#?

Upvotes: 0

Related Questions