如何扩展dataGridView内置的行拖放功能

本文关键字:内置 拖放 功能 dataGridView 何扩展 扩展 | 更新日期: 2023-09-27 18:07:59

我已经能够使两个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);
            }
        }
    }
}

如何扩展dataGridView内置的行拖放功能

您在事件委托之间定义错误:protected override void OnDragEnter(DragEventArgs e) { }是一个方法,它调用数据网格的事件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
}

覆盖是在DataGridView本身。只需将"sender"替换为"this",就可以了。