簡(jiǎn)單講述VB.NET表間拖放
經(jīng)過(guò)長(zhǎng)時(shí)間學(xué)習(xí)VB.NET表間拖放,于是和大家分享一下,看完本文你肯定有不少收獲,希望本文能教會(huì)你更多東西。
VB.NET表間拖放
VB.NET表間拖放有一個(gè)情況是從一個(gè)列表移動(dòng)項(xiàng)目到另一個(gè)列表。這種情況下拖放將變得更加簡(jiǎn)單。向窗體中添加兩個(gè)ListView控件,并把他們的AllowDrop、Multiselect、View屬性分別設(shè)置成True、True、List。并添加如下代碼:
- Private Sub ListView_ItemDrag(ByVal sender As Object, ByVal e As _
- System.Windows.Forms.ItemDragEventArgs) Handles ListView1.ItemDrag, _
- ListView2.ItemDrag
- Dim myItem As ListViewItem
- Dim myItems(sender.SelectedItems.Count - 1) As ListViewItem
- Dim i As Integer = 0
- ' Loop though the SelectedItems collection for the source.
- For Each myItem In sender.SelectedItems
- ' Add the ListViewItem to the array of ListViewItems.
- myItems(i) = myItem
- ii = i + 1
- Next
- ' Create a DataObject containg the array of ListViewItems.
- sender.DoDragDrop(New _
- DataObject(System.Windows.Forms.ListViewItem(), myItems), _
- DragDropEffects.Move)
- End Sub
- Private Sub ListView_DragEnter(ByVal sender As Object, ByVal e As _
- System.Windows.Forms.DragEventArgs) Handles ListView1.DragEnter, _
- ListView2.DragEnter
- ' Check for the custom DataFormat ListViewItem array.
- If e.Data.GetDataPresent(System.Windows.Forms.ListViewItem()) Then
- e.Effect = DragDropEffects.Move
- Else
- e.Effect = DragDropEffects.None
- End If
- End Sub
- Private Sub ListView_DragDrop(ByVal sender As Object, ByVal e As _
- System.Windows.Forms.DragEventArgs) Handles ListView1.DragDrop, _
- ListView2.DragDrop
- Dim myItem As ListViewItem
- Dim myItems() As ListViewItem = _ e.Data.GetData(System.Windows.Forms.ListViewItem())
- Dim i As Integer = 0
- For Each myItem In myItems
- ' Add the item to the target list.
- sender.Items.Add(myItems(i).Text)
- ' Remove the item from the source list.
- If sender Is ListView1 Then
- ListView2.Items.Remove(ListView2.SelectedItems.Item(0))
- Else
- ListView1.Items.Remove(ListView1.SelectedItems.Item(0))
- End If
- ii = i + 1
- Next
- End Sub
你可能不明白為什么這個(gè)例子中用的是ListView控件而不是ListBox控件,這個(gè)問(wèn)題題的好,因?yàn)長(zhǎng)istBox控件不支持多項(xiàng)拖放。ListView和TreeView控件有個(gè)ItemDrag事件。上面的例子中,一個(gè)ItemDrag事件句柄覆蓋了兩個(gè)控件,并在列在Handles從句。Sender參數(shù)表明哪個(gè)控件正在初始化Drag。因?yàn)镈ataFormats類(lèi)沒(méi)有ListViewItem類(lèi)型成員,數(shù)據(jù)必須傳遞給一個(gè)系統(tǒng)類(lèi)型。ItemDrag創(chuàng)建了一個(gè)ListViewItem類(lèi)型的數(shù)組,并用一個(gè)循環(huán)來(lái)遍歷SelectedItem集合。在DoDragDrop方法中,創(chuàng)建了一個(gè)新的DataObject并用數(shù)組來(lái)來(lái)對(duì)它進(jìn)行操作??梢杂眠@種方法來(lái)拖放任何系統(tǒng)類(lèi)型。
VB.NET表間拖放結(jié)論:
正像你從這些例子中所看到的一樣,為應(yīng)用程序添加拖放操作并不是很難。當(dāng)你理解了這些基本的技巧后,你就可以為你自己的程序添加拖放的代碼了 。
【編輯推薦】