views:

56

answers:

2

When I copy data from my application, I wrote a simple C# script to check what type it is. Apparently (and I expected that), it's an array of strings:

       IDataObject data = Clipboard.GetDataObject();
       Console.WriteLine(data.GetFormats(true)); // writes "System.String[]"

Now when I extract the data like

      object o = data.GetData( "System.String[]" );

the resulting object stays null.

Why? How am I to extract the data?

+3  A: 

You are not supposed to put the CLR types as parameters. The parameter to GetData is just an identifier that can be anything, but there are some pre-defined formats which many programs use.

What you probably want to do is use DataFormats.Text to retrieve the data in text form (i.e. a string). Note that this only works if the source of the clipboard contents actually provided data in this format, but most do so you should be safe.

And, since text is such a common format, there's even a convenience method to retrieve it in that format called Clipboard.GetText()

EDIT: The string[] you get back when you call GetFormats is just an array of strings listing all the available formats. It's not the actual clipboard data, it just tells you which format you can get it in when you do obj.GetData(). Look at that array in the debugger or print it in a foreach to see if there's any format that is array-like.

Isak Savo
I know the data is copied from a range of grid cells. That's why I strongly believe the `String[]` format. I am investigating the reason why copying these specific cells doesn't work, while others do.
xtofl
+1  A: 

data.GetFormats(true) by MSDN returns names of data formats that are stored inside the clipboard along with all data formats that those formats in clipboard can be converted to. To get data you need to call data.GetData(dataFormatName) of data format you want to get. If you want to get all the objects you should do this:

foreach (var item in data.GetFormats(true))
{
   object o = data.GetData(item);
   // do something with o
}
Ivan Ferić