Showing posts with label clipboard. Show all posts
Showing posts with label clipboard. Show all posts

Sunday, June 17, 2007

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

It is often useful to be able to copy the contents of a ListView to the Windows Clipboard. I have written a function for VB.NET, C#, and VB6 called CopyListViewToClipboard that will copy the contents of a ListView (in Details mode) to the Windows Clipboard. Additional functions are also available for a ListBox control here. The column headers will be the first row and the items in the listview will be the remaining rows. To make the copied data more compatible with applications like Excel, a tab character is placed between items in a row and a carriage return/linefeed is placed at the end of the row.

Here is an example ListView with some data in it:



Here is what is copied to the clipboard and then to Excel:




VB.NET:

Imports System.text

...


Public Sub CopyListViewToClipboard(ByVal lv As ListView)

Dim buffer As New StringBuilder

For i As Integer = 0 To lv.Columns.Count - 1
buffer.Append(lv.Columns(i).Text)
buffer.Append(vbTab)
Next

buffer.Append(vbCrLf)

For i As Integer = 0 To lv.Items.Count - 1
For j As Integer = 0 To lv.Columns.Count - 1
buffer.Append(lv.Items(i).SubItems(j).Text)
buffer.Append(vbTab)
Next
buffer.Append(vbCrLf)
Next

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

End Sub


C#

using System.Text;

...


public void CopyListViewToClipboard(ListView lv)
{
StringBuilder buffer = new StringBuilder();

for (int i = 0; i < lv.Columns.Count; i++)
{
buffer.Append(lv.Columns[i].Text);
buffer.Append("\t");
}

buffer.Append("\n");

for (int i = 0; i < lv.Items.Count; i++)
{
for (int j = 0; j < lv.Columns.Count; j++)
{
buffer.Append(lv.Items[i].SubItems[j].Text);
buffer.Append("\t");
}

buffer.Append("\n");
}

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


VB6


Public Sub CopyListViewToClipboard(lv As ListView)

Dim buf As String
Dim i As Integer
Dim j As Integer

For i = 1 To lv.ColumnHeaders.count

buf = buf + lv.ColumnHeaders.Item(i).Text + vbTab

Next


buf = buf + vbCrLf

For i = 1 To lv.ListItems.count

buf = buf + lv.ListItems(i).Text

For j = 1 To lv.ColumnHeaders.count - 1
buf = buf + vbTab + lv.ListItems(i).SubItems(j)
Next

buf = buf + vbCrLf

Next

buf = buf + vbCrLf

Clipboard.Clear
Clipboard.SetText buf

End Sub