1

我有一个带有DataGridView控件的WINFORM应用程序,连接到ContextMenuStrip控件中。 ContextMenuStrip触发事件实质上在DataGridView剪贴板之间执行复制/粘贴。

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();
}

我在我的应用程序中添加了另一个DataGridView并希望在它们之间共享ContextMenuStrip,因为根据我上面的代码,它被硬编码到我的网格myGrid中。

我相信修改我的代码以从发送者投射一个新的DataGridView控件将是一个简单的练习:

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);
}

但当然,我发现发件人ToolStripMenuItem

有没有办法通过senderEventArgs e引用原始DataViewGrid

并且,感谢您阅读 :)

4

2 回答 2

2

啊,我想我明白了!

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);
}

我在这里找到了解决方案:http: //discuss.joelonsoftware.com/default.asp? dotnet.12.474610.5

最后根据这个线程,我想将ToolStripMenuItem添加为线程标签,但我没有代表。感谢代表将其添加到标签缓存中的人,以便我可以更新此踏板;希望让别人的生活,同样的问题,更容易找到这个线程!:)

于 2012-07-20T14:23:44.340 回答
0

尝试

var grid = CType(sender, DataGridView)

或者

var grid = CType(sender.parent, DataGridView)
于 2012-07-19T18:22:04.717 回答