Search code examples
c#winformslistviewdrag

Create auto scroll on listview when dragging over an item


How to create auto scroll on listview dragOver.

I did it the following way:

private void groupsCharacterListView_DragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(List<ListViewItem>)))
            {
                groupsCharacterListView.DragOver += RevealMoreItems;
                groupsCharacterListView.DragOver += (source, e) =>
                {
                    e.Effect = DragDropEffects.Move;
                };
            }
        }
private static void RevealMoreItems(object sender, DragEventArgs e)
        {
            var listView = (ListView)sender;

            var point = listView.PointToClient(new Point(e.X, e.Y));
            var item = listView.GetItemAt(point.X, point.Y);
            if (item == null)
                return;

            var index = item.Index;
            var maxIndex = listView.Items.Count;
            var scrollZoneHeight = listView.Font.Height;
            listView.PointToScreen(new Point(e.X, e.Y + 40));

            if (index > 0 && point.Y < scrollZoneHeight)
            {
                listView.Items[index - 1].EnsureVisible();
            }
            else if (index < maxIndex && point.Y > listView.Height - scrollZoneHeight)
            {
                listView.Items[index + 1].EnsureVisible();
            }
        }

but it gives me the following error:

A local or parameter named 'e' cannot be declared in this scope because that is used in an enclosing local scope to define a local or parameter.


Solution

  • The error description is quite clear. You cannot use e at this lines because it's already used in your event handler.

    Here at the event handler:

    private static void RevealMoreItems(object sender, DragEventArgs e) 
    

    and here in the code:

    var point = listView.PointToClient(new Point(e.X, e.Y));
    
    listView.PointToScreen(new Point(e.X, e.Y + 40));
    

    Try to use another variable name.