VB.Net程序设计:ListBox拖动项排序代码和两个ListBox操作
常用于:左边的listbox添加到右边的listbox。
简单代码。供自己用。
'Dim _listA, _listB As New List(Of String)
'Dim indexofsource As Integer '//拖动的起始索引
'Dim indexoftarget As Integer '//拖动的结束索引
'......
Private Sub LstB_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles LstB.DragDrop
Dim lb As ListBox = CType(sender, ListBox)
indexoftarget = lb.IndexFromPoint(lb.PointToClient(New Point(e.X, e.Y)))
If (indexoftarget <> ListBox.NoMatches) Then
Dim temp As String = lb.Items(indexoftarget).ToString()
lb.Items(indexoftarget) = lb.Items(indexofsource)
lb.Items(indexofsource) = temp
lb.SelectedIndex = indexoftarget
End If
End Sub
Private Sub LstB_DragOver(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles LstB.DragOver
'//拖动源和放置的目的地一定是一个ListBox
If (e.Data.GetDataPresent(GetType(Integer)) And (CType(sender, ListBox)).Equals(Me.LstB)) Then
e.Effect = DragDropEffects.Move
Else
e.Effect = DragDropEffects.None
End If
End Sub
Private Sub LstB_MouseMove(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles LstB.MouseMove
If e.Button = Windows.Forms.MouseButtons.Left Then
indexofsource = (CType(sender, ListBox)).IndexFromPoint(e.X, e.Y)
If (indexofsource <> ListBox.NoMatches) Then 'NoMatches=-1
'CType(sender, ListBox).DoDragDrop(CType(sender, ListBox).Items(indexofsource).ToString(), DragDropEffects.All)
CType(sender, ListBox).DoDragDrop(indexofsource, DragDropEffects.All)
End If
End If
End Sub
Private Sub BtnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnAdd.Click
If Me.LstA.SelectedItems.Count = 1 Then
If Me._listB.Contains(Me._listA.Item(Me.LstA.SelectedIndex)) = False Then
Me._listB.Add(Me._listA.Item(Me.LstA.SelectedIndex))
ShowListB()
End If
End If
End Sub
Private Sub BtnAddAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnAddAll.Click
_listB.Clear()
For Each s As String In _listA
_listB.Add(s)
Next
ShowListB()
End Sub
Private Sub BtnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnRemove.Click
If Me.LstB.SelectedItems.Count = 1 Then
_listB.RemoveAt(Me.LstB.SelectedIndex)
ShowListB()
End If
End Sub
Private Sub BtnRemoveAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnRemoveAll.Click
_listB.Clear()
Me.LstB.Items.Clear()
End Sub