1
votes

I have a WINFORM app with a DataGridView control , hooked into a ContextMenuStrip control.
The ContextMenuStrip fires events to essentially perform copy / paste between the DataGridView and the Clipboard.

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
  CopyClipboard();
}

private void CopyClipboard()
{
  DataObject d = myGrid.GetClipboardContent();
  Clipboard.SetDataObject(d);
}

private void pasteCtrlVToolStripMenuItem_Click(object sender, EventArgs e)
{
  PasteClipboard();
}

I've added another DataGridView to my application and wish to share ContextMenuStrip between them since, per my code above, it's hardcoded to my grid, myGrid.

I believed it would simply be an easy exercise to modify my code to cast a new DataGridView control from the sender:

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
  CopyClipboard(sender);
}

private void CopyClipboard(object sender)
{
  var grid = (DataGridView)sender;
  DataObject d = grid.GetClipboardContent();
  Clipboard.SetDataObject(d);
}

private void pasteCtrlVToolStripMenuItem_Click(object sender, EventArgs e)
{
 var grid = (DataGridView)sender;
  PasteClipboard(grid);
}

but of course, I found that the sender was instead the ToolStripMenuItem.

Is there a way to reference the original DataViewGrid via the sender, or EventArgs e ?

And, thank you for reading :)

2

2 Answers

2
votes

Ahh, think I got it!

private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
  CopyClipboard(sender);
}

private void CopyClipboard(object sender)
{
  var grid = (DataGridView)sender;
  DataObject d = grid.GetClipboardContent();
  Clipboard.SetDataObject(d);
}

private void pasteCtrlVToolStripMenuItem_Click(object sender, EventArgs e)
{
  var item = (ToolStripMenuItem)sender;

  ToolStripMenuItem t = (ToolStripMenuItem)sender;
  ContextMenuStrip s = (ContextMenuStrip)t.Owner;

  var grid = (DataGridView)s.SourceControl;

  // Pulling the backend datatable just to enhance the example.
  // Going Live, the consumer of the "grid" will do the extraction.
  BindingSource bs = (BindingSource)grid.DataSource;
  DataTable dt = (DataTable)bs.DataSource;


  PasteClipboard(grid, dt);
}

I found the solution here: http://discuss.joelonsoftware.com/default.asp?dotnet.12.474610.5

Finally per this thread, I wanted to add ToolStripMenuItem as a thread tag but i don't have the rep. Appreciate someone with the rep adding it to the tag cache so that I can update this tread; hopefully making somone else's life, with same issue, a lil' easier finding this thread! :)

0
votes

Try

var grid = CType(sender, DataGridView)

or

var grid = CType(sender.parent, DataGridView)