Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listview with copy-paste

Is there an easy way of adding copy-paste for a listview, or should I just switch to DataGridView instead?

My application is kinda like an address book, it contains emails, numbers etc where copy paste would be useful.

like image 335
Zubirg Avatar asked Jun 12 '10 18:06

Zubirg


3 Answers

The example below handles the Ctrl-C as a copy to the clipboard command, and copies the second column's value from all the selected rows:

    private void resultsListView_KeyUp(object sender, KeyEventArgs e)
    {
        if (sender != resultsListView) return;

        if (e.Control && e.KeyCode == Keys.C)
            CopySelectedValuesToClipboard();
    }

    private void CopySelectedValuesToClipboard()
    {
        var builder = new StringBuilder();
        foreach (ListViewItem item in resultsListView.SelectedItems)
            builder.AppendLine(item.SubItems[1].Text);

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

Use item.Text for the first column, and item.SubItems[n].Text for other columns.

References:

  1. What is the KeyChar for Ctrl+C and Ctrl+V in C# to get the keys and proper event handler.
  2. Copy ListView to Clipboard in VB.NET, C#, and VB6 for full example of copying ListView to the Clipboard.
like image 194
Brett Avatar answered Oct 18 '22 03:10

Brett


It's not very difficult to do manual copy and paste, just put in an event handler for KeyDown (or maybe it's KeyPress can't remember but fairly sure it's one of them) and check what key is pressed by looking at e.KeyCode and check if e.Control is true. If it's one of x, c or v just call Clipboard.SetText or Clipboard.GetText to write/read to/from the clipboard.
See here for the MSDN documentation of the Clipboard class.

You could add a context menu with Copy and Paste on to the ListView also to make it complete.

like image 42
Hans Olsson Avatar answered Oct 18 '22 02:10

Hans Olsson


I've made it as method (depending on @brett's top answer), so just execute once on Form initialization: copyableListView(myListView) and it will do itself.

Code:

private void copyableListView(ListView listView)
{
    listView.KeyDown += (object sender, KeyEventArgs e) =>
    {
        if (!(sender is ListView)) return;

        if (e.Control && e.KeyCode == Keys.C)
        {
            var builder = new StringBuilder();
            foreach (ListViewItem item in (sender as ListView).SelectedItems)
                builder.AppendLine(item.Text + Environment.NewLine);
            Clipboard.SetText(builder.ToString());
        }
    };
}

Also, on form destroy, you should have method to remove all subscribed-events, i.e.

void myDeinit()
{
    myListView=null;
    myListView2=null;
    ...
}
like image 1
T.Todua Avatar answered Oct 18 '22 02:10

T.Todua