User124726 User124726 - 4 months ago 18
Vb.net Question

Copy/Paste Items from listbox to any doc (Excel, Word, .txt) -- VB.NET

I'm unable to copy/paste items from my listbox to any document (Excel, Word, .txt). I would need to select multiple items in the listbox. I searched for it but there seem to be multiple vague answers around there. Can anyone guide me?

Thanks!

Answer

All you need to do is allow SelectionMode to MultiSimple or MultiExtended then you can use SelectedItems collection to copy to clipboard in KeyDown event of listbox

Simply put

ListBox1.SelectionMode = SelectionMode.MultiSimple in form.load Event

and use this code (note: listbox is named as ListBox1)

Private Sub ListBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles ListBox1.KeyDown

    If e.Control AndAlso e.KeyCode = Keys.C Then
        Dim copy_buffer As New System.Text.StringBuilder
        For Each item As Object In ListBox1.SelectedItems
            copy_buffer.AppendLine(item.ToString)
        Next
        If copy_buffer.Length > 0 Then
            Clipboard.SetText(copy_buffer.ToString)
        End If
    End If
End Sub
Comments