ToolStripMenuItem_Click(object sender,EventArgs e) - 转换回DataGridView

时间:2012-07-19 18:11:59

标签: c# datagridview casting contextmenustrip sender

我有一个带有 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

有没有办法通过发件人 EventArgs e 引用原始 DataViewGrid

并且,感谢您阅读:)

2 个答案:

答案 0 :(得分: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 作为主题标签,但我没有代表。 感谢某人将其添加到标记缓存中,以便我可以更新此内容; 希望能够以同样的问题制造别人的生活,一个人能够轻松找到这个主题! :)

答案 1 :(得分:0)

尝试

var grid = CType(sender, DataGridView)

var grid = CType(sender.parent, DataGridView)