#707 – Dragging a List of Items from a WPF Application into Excel

You can use drag-and-drop in WPF to drag a comma-separated list of values into Excel.  When you drop a CSV list into Excel, it will automatically put each item into a different cell.

In the example below, we have a list of items in a ListBox.

707-001

We can drag the list of items by handling the MouseLeftButtonDown event for the blue label.  We create a string containing a comma-separated list of the items.  We then create a DataObject with a format of CommaSeparatedValue.

        private void Label_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            List<string> stringItems = new List<string>();

            foreach (ListBoxItem lbi in lbEncyclopedias.Items)
                stringItems.Add((string)lbi.Content);

            string someValues = string.Join(",", stringItems);

            DataObject data = new DataObject(DataFormats.CommaSeparatedValue, someValues);

            DragDrop.DoDragDrop((DependencyObject)e.Source, data, DragDropEffects.Copy);
        }

When we drag this data to Excel, it shows the destination range during the drag.

707-002

When we release the mouse button, the items from the list are dropped into cells in this range.

707-003

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #707 – Dragging a List of Items from a WPF Application into Excel

  1. Pingback: Dew Drop – December 7, 2012 (#1,458) | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: