Sunday, June 17, 2007

Copy ListBox to Clipboard in VB.NET, C#, and VB6

Here is a function I have written in VB.NET, C#, and VB6 to copy the contents of a ListBox to the Windows Clipboard. If you are interested in copying a ListView to the clipboard, see this posting.


VB.NET:


Imports System.text

...

Public Sub CopyListBoxToClipboard(ByVal lb As ListBox)

Dim buffer As New StringBuilder

For i As Integer = 0 To lb.Items.Count - 1
buffer.Append(lb.Items(i).ToString)
buffer.Append(vbCrLf)
Next

My.Computer.Clipboard.SetText(buffer.ToString)

End Sub


C#:

using System.Text;

...

public void CopyListBoxToClipboard(ListBox lb)
{
StringBuilder buffer = new StringBuilder();

for (int i = 0; i < lb.Items.Count; i++)
{
buffer.Append(lb.Items[i].ToString());
buffer.Append("\n");
}

Clipboard.SetText(buffer.ToString());
}



VB6:

Public Sub CopyListBoxToClipboard(lb As ListBox)

Dim buf As String

Dim i As Long

For i = 0 To lb.ListCount - 1

buf = buf + lb.List(i)

buf = buf + vbCrLf

Next

Clipboard.Clear
Clipboard.SetText buf

End Sub

5 comments:

Dulari said...

I am not able to get this code running in vb.net. I dont get the option " clipboard" when i type my.computer......Can you please help me? do i need to add any assembly ?

srego said...

You can look up the Clipboard object in the online help and see the requirements, but it looks like it is supported by all projects except Web Control and Web Site projects.

Anonymous said...

this code is exactly what I needed. One thing, though. You can use buffer.AppendLine and it will include the newline as opposed to making a separate append statement.

Anonymous said...

Hi, did you remember the declaration:

Imports System.text

lingmaaki said...

C# Listbox Example

Ling