我已经能够使2 C#winform datagridviews在它们之间拖放行,但它使用了大量代码。现在我正在寻找创建一个包含10个这样的网格的表单,我正在尝试重用代码。我以为我可以简单地创建一个DataGridView的子类并添加事件处理程序,但是我遇到了麻烦。
具体来说,当智能感知的唯一事件没有正确的签名时,如何覆盖onDragDrop事件。
我看到的签名如下:protected override void OnDragDrop(DragEventArgs e)
,但我期待签名protected override void OnDragDrop(object sender, DragEventArgs e)
,因为我在代码中使用了发件人。我错过了什么?我该如何正确覆盖此事件?我的非工作代码如下:
public class DragGrid : DataGridView
{
private DragGrid()
{
}
private DragGrid(DataTable table)
{
this.DataSource = table;
}
protected override void OnDragEnter(DragEventArgs e)
{
base.OnDragEnter(e);
e.Effect = DragDropEffects.Copy;
}
protected override void OnDragDrop(DragEventArgs e)
{
base.OnDragDrop(e);
DataGridView grid = sender as DataGridView;
DataTable table = grid.DataSource as DataTable;
DataRow row = e.Data.GetData(typeof(DataRow)) as DataRow;
if (row != null && table != null && row.Table != table)
{
table.ImportRow(row);
row.Delete();
table.AcceptChanges();
}
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
DragGrid.HitTestInfo info = ((DragGrid)this).HitTest(e.X, e.Y);
if (info.RowIndex >= 0)
{
DataRow view = ((DataTable)(this.DataSource)).Rows[info.RowIndex];
if (view != null)
{
this.DoDragDrop(view, DragDropEffects.Copy);
}
}
}
}
答案 0 :(得分:1)
您在事件和委托之间的定义中犯了错误:
protected override void OnDragEnter(DragEventArgs e) { }
是方法,可以调用您的数据网格的event DragEnter
。
当这个事件诅咒时,所有带有签名protected override void OnDragEnter(object sender, DragEventArgs e) { }
的委托都会被调用。
所以你无法覆盖事件 - 这只是一个字段。你可以覆盖调用它的方法,但我认为这不是你想要的。我建议你在构造函数中为脚本添加DragEnter
事件的处理程序:
private DragGrid(DataTable table)
{
this.DataSource = table;
this.DragEnter += new DragEventHandler(_onDragEnter);
}
private void _onDragEnter(object sender, DragEventArgs e)
{
// your code here
}
答案 1 :(得分:1)
覆盖在DataGridView本身内。只需将'sender'替换为'this'即可,您将全部设置好。