title: C# .NET WinForms How do I copy instance of class from one List<class> to another List<class> using Clipboard
body: <p>I'm writing a C# .NET WinForms app which contains two DataGridView controls, each with its own List:</p>
  
  <p>DataGridView1, List1
  DataGridView2, List2</p>
  
  <p>FYI: DataItem is a class consisting of integers, strings, booleans, etc., and all items listed in each datagridview control are also listed in its corresponding List.</p>
  
  <p>The user will right-click on a DataGridView1 and in the resulting context menu, click "Copy Item" to copy a DataItem from List1 to the clipboard...</p>
  
  <pre><code>    private void ctxtContextMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
      {
          int SelectedRowIndex = DataGridView1.SelectedRows[0].Index;
          if (ctxtCopyItem == e.ClickedItem)
          {
              Clipboard.SetDataObject(List1[SelectedRowIndex]);
          }
          else if (ctxtPasteItem == e.ClickedItem)
          {
              PasteDataItem();
          }
       }
  </code></pre>
  
  <p>The user will then go to DataGridView2, right-click on it and in the context menu, click "Paste Item" to add that DataItem to DataGridView2 and to List2...</p>
  
  <pre><code>    private void PasteDataItem()
      {
          DataItem dataitem = new DataItem();
          dataitem = Clipboard.GetDataObject());   // This line is where the error occurs.
          List2.Add(dataItem); 
          UpdateDataGridView2();
       }
  </code></pre>
  
  <p>And here's the code for the context menu's Opening EventHandler...</p>
  
  <pre><code>    private void ctxtContextMenu_Opening(object sender, CancelEventArgs e)
      {
          // If clipboard contains a DataItem, enable ctxtPasteItem...
          if (Clipboard.GetDataObject() is DataItem)
              ctxPasteQuestion.Enabled = true;
      }
  </code></pre>
  
  <p>In the method "PasteDataItem()" above, an exception occurs:</p>
  
  <p>System.InvalidCastException occurred
    HResult=0x80004002
    Message=Unable to cast object of type 'System.Windows.Forms.DataObject' to type 'DataItem'.</p>
  
  <p>Apparently, I'm either not copying DataItem to the clipboard correctly or I'm not retrieving it from the clipboard correctly. One possible cause is that I'm not casting the DataItem properly. I haven't found any online tutorials on casting, copying and pasting an instance of a class using the clipboard. Is this even possible and if so, what's the right way to get that class instance to and from the Clipboard?</p>