【问题标题】:drag and drop to checkedlistbox拖放到选中列表框
【发布时间】:2013-04-04 18:19:57
【问题描述】:

我有一个选中的列表框,我只想拖放图像扩展名而不是文本文件。 那么我该如何完成它。 我可以拖放所有文件格式,但我只需要图像文件。 这是我的代码:

Private Sub CheckedListBox1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles CheckedListBox1.DragDrop

    Dim Files As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
    For Each FileName As String In Files
        CheckedListBox1.Items.Add(FileName, CheckState.Checked)
        Thumbcontrol1.AddThumbnail(FileName)
    Next
End Sub

Private Sub CheckedListBox1_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles CheckedListBox1.DragEnter
    If e.Data.GetDataPresent(DataFormats.FileDrop) Then
        e.Effect = DragDropEffects.Copy
    End If
End Sub

【问题讨论】:

  • 你不能检查每个FileName的扩展名吗?
  • 我知道但是如何添加代码是我的问题?
  • 只需交换 for 循环中的两个语句。所以当图片加载代码失败时它不会被添加。

标签: vb.net drag-and-drop


【解决方案1】:

只需检查每个文件名的扩展名。

Private Shared ReadOnly SupportedExtensions As String() = {".jpg", ".jpeg", ".gif"}

Private Sub CheckedListBox1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles CheckedListBox1.DragDrop
    Dim Files As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
    For Each FileName As String In Files
        Dim Extension As String = Path.GetExtension(FileName).ToLower
        If Array.IndexOf(SupportedExtensions, Extension) <> -1 Then
            CheckedListBox1.Items.Add(FileName, CheckState.Checked)
            Thumbcontrol1.AddThumbnail(FileName)
        End If
    Next
End Sub

如果拖动的文件列表中没有图片文件,您可能需要在 DragEnter 方法中添加类似的代码以显示DragDropEffects.None

【讨论】:

  • 非常感谢您的快速回复,您真的节省了我的时间。
【解决方案2】:

类似这样的东西(你需要添加更多的文件扩展名):

Dim Files As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
For Each FileName As String In Files
    If FileName.Contains(".jpg") Or FileName.Contains(".bmp") Then
       CheckedListBox1.Items.Add(FileName, CheckState.Checked)
       Thumbcontrol1.AddThumbnail(FileName)
    End If
Next

您还需要考虑文件名的大小写。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 2012-07-27
    • 2013-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多