簡(jiǎn)單講解VB.NET ListBox控件
VB.NET還是比較常用的,于是我研究了一下VB.NET ListBox控件,在這里拿出來(lái)和大家分享一下,希望對(duì)大家有用。在windows中拖放通常是復(fù)制或移動(dòng)文件,windows完全支持該功能,而且對(duì)許多用戶(hù)來(lái)說(shuō)這也是操作文件的優(yōu)選方式。除此之外,用戶(hù)已經(jīng)習(xí)慣了把文件拖動(dòng)到一個(gè)程序來(lái)打開(kāi)文件的方式,像拖動(dòng)一個(gè)doc文件到word來(lái)打開(kāi)。
在這個(gè)例子中用從windows資源管理器拖來(lái)的文件來(lái)操作VB.NET ListBox控件。向窗體中添加一個(gè)VB.NET ListBox控件,并設(shè)置其AllowDrop屬性為T(mén)rue,并添加如下代碼:
- 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。因?yàn)槲募旧聿⒉皇钦娴木捅粡?fù)制或移動(dòng)了,因此源控件設(shè)置成哪個(gè)AllowedEffects并沒(méi)有關(guān)系,所以指定All對(duì)任何FileDrop都可以。
在上面的例子中FileDrop格式包含了每個(gè)被拖動(dòng)文件的全路徑。
【編輯推薦】