Oliver Salzburg
Oliver Salzburg

Reputation: 22099

How to store a Collection of Objects in the Clipboard?

I have a class Slide, of which I want to place several instances in the clipboard. It works perfectly fine for a single instance.
But when I try to, for example, put a List<Slide> in the clipboard, the SetDataObject call will silently fail.
Internally, a COMException will be thrown and is swallowed. This is because List does not implement ISerializeable.
So, List<T> seems not to be an option. What would be the proper approach to place a collection of Slide instances in the clipboard?

Upvotes: 3

Views: 5323

Answers (2)

Oliver Salzburg
Oliver Salzburg

Reputation: 22099

Turns out my assumptions were incorrect. I simply forgot a ToList() call and was only passing in the IEnumerable to SetData. After adding that, it is put into the clipboard just fine.

This is the code I ended up using back then:

public void CopySelectedSlidesToClipboard() {
  // Construct data format for Slide collection
  DataFormats.Format dataFormat = DataFormats.GetFormat( typeof( List<Slide> ).FullName );

  // Construct data object from selected slides
  IDataObject dataObject = new DataObject();

  List<Slide> dataToCopy = SelectedSlides.ToList();
  dataObject.SetData( dataFormat.Name, false, dataToCopy );

  // Put data into clipboard
  Clipboard.SetDataObject( dataObject, false );
}

public void PasteSlidesFromClipboard() {
  // Get data object from the clipboard
  IDataObject dataObject = Clipboard.GetDataObject();
  if( dataObject != null ) {
    // Check if a collection of Slides is in the clipboard
    string dataFormat = typeof( List<Slide> ).FullName;
    if( dataObject.GetDataPresent( dataFormat ) ) {
      // Retrieve slides from the clipboard
      List<Slide> slides = dataObject.GetData( dataFormat ) as List<Slide>;
      if( slides != null ) {
        Slides = Slides.Concat( slides ).ToList();
      }
    }
  }
}

Upvotes: 1

MCain
MCain

Reputation: 465

ArrayList is serializable. While you lose the strong typing, you can always cast on the way out.

Upvotes: 1

Related Questions