You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现ListView控件的多项目同时拖放功能?

实现ListView控件间批量拖放多个项

当然可以实现一次拖放多个项,只需对现有代码做如下关键修改,核心逻辑是遍历源ListView的所有选中项,逐一处理复制与删除操作:

关键改动要点

  • 遍历源ListView的SelectedItems集合,替代原代码中仅处理单个SelectedItem的逻辑
  • 倒序删除选中项(正序删除会导致后续项的索引发生偏移,引发错误)
  • 为每个选中项复制完整的内容(包括主项和子项),并插入到目标ListView的指定位置

修改后的完整代码

' 模块级变量保持不变:DragSource、DropTargetIndex
Private Sub ListView1_OLEDragDrop(Index As Integer, Data As MSComctlLib.DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, y As Single)
    Dim n As Long, li As ListItem
    Dim targetIndex As Long
    Dim selectedCount As Integer
    
    DropTargetIndex = Index
    If Index = 1 And ListView1(1).ListItems.Count > 0 Then Exit Sub
    
    ' 获取目标插入位置
    If ListView1(Index).DropHighlight Is Nothing Then
        targetIndex = ListView1(Index).ListItems.Count + 1
    Else
        targetIndex = ListView1(Index).DropHighlight.Index
    End If
    
    ' 倒序遍历选中项,避免删除时索引偏移
    selectedCount = ListView1(DragSource).SelectedItems.Count
    For n = selectedCount To 1 Step -1
        Set li = ListView1(DragSource).SelectedItems(n)
        
        ' 复制项到目标ListView
        With ListView1(Index).ListItems.Add(targetIndex, li.Key, li.Text, li.Icon, li.SmallIcon)
            Dim subItem As ListSubItem
            For Each subItem In li.ListSubItems
                .ListSubItems.Add , subItem.Key, subItem.Text
            Next
            .Selected = True
        End With
        
        ' 从源ListView删除项
        ListView1(DragSource).ListItems.Remove li.Index
    Next n
    
    Set ListView1(Index).DropHighlight = Nothing
End Sub

Private Sub ListView1_OLEDragOver(Index As Integer, Data As MSComctlLib.DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, y As Single, State As Integer)
    If Index = 0 And ListView1(1).ListItems.Count > 0 Then Exit Sub
    Set ListView1(Index).DropHighlight = ListView1(Index).HitTest(X, y)
End Sub

Private Sub ListView1_OLEStartDrag(Index As Integer, Data As MSComctlLib.DataObject, AllowedEffects As Long)
    If Index = 0 And ListView1(1).ListItems.Count > 0 Then Exit Sub
    DragSource = Index
    AllowedEffects = vbDropEffectMove
End Sub

补充说明

  • 倒序遍历是核心:如果正序删除选中项,删除第一个项后,后续选中项的索引会自动前移,导致循环时跳过部分项或引用不存在的索引
  • 所有选中项会被插入到目标ListView的同一位置(DropHighlight指定的位置),保持选中项的原有顺序
  • 复制逻辑完整保留了原项的Key、Text、图标以及所有子项,确保数据一致性

内容的提问来源于stack exchange,提问作者user3387046

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 05:10:32