簡單講解VB.NET ListBox控件
VB.NET還是比較常用的,于是我研究了一下VB.NET ListBox控件,在這里拿出來和大家分享一下,希望對大家有用。在windows中拖放通常是復(fù)制或移動文件,windows完全支持該功能,而且對許多用戶來說這也是操作文件的優(yōu)選方式。除此之外,用戶已經(jīng)習(xí)慣了把文件拖動到一個程序來打開文件的方式,像拖動一個doc文件到word來打開。
在這個例子中用從windows資源管理器拖來的文件來操作VB.NET ListBox控件。向窗體中添加一個VB.NET ListBox控件,并設(shè)置其AllowDrop屬性為True,并添加如下代碼:
- Private Sub ListBox1_DragEnter(ByVal sender As Object, ByVal e As _
- System.Windows.Forms.DragEventArgs) Handles ListBox1.DragEnter
- If e.Data.GetDataPresent(DataFormats.FileDrop) Then
- e.Effect = DragDropEffects.All
- End If
- End Sub
- Private Sub ListBox1_DragDrop(ByVal sender As Object, ByVal e As _
- System.Windows.Forms.DragEventArgs) Handles ListBox1.DragDrop
- If e.Data.GetDataPresent(DataFormats.FileDrop) Then
- Dim MyFiles() As String
- Dim i As Integer
- ' Assign the files to an array.
- MyFiles = e.Data.GetData(DataFormats.FileDrop)
- ' Loop through the array and add the files to the list.
- For i = 0 To MyFiles.Length - 1
- ListBox1.Items.Add(MyFiles(i))
- Next
- End If
- End Sub
你可能已經(jīng)注意到了DragEnter事件中的Effect屬性被設(shè)置成DragDropEffects.All。因為文件本身并不是真的就被復(fù)制或移動了,因此源控件設(shè)置成哪個AllowedEffects并沒有關(guān)系,所以指定All對任何FileDrop都可以。
在上面的例子中FileDrop格式包含了每個被拖動文件的全路徑。
【編輯推薦】