How to extend dataGridView built in row drag and drop
I've been able to make 2 C# 开发者_JAVA百科winform datagridviews drag and drop rows between them, but it uses a lot of code. Now I'm looking at creating a form that will contain 10 such grids, and I'm trying to reuse the code. I thought I could simply make a sub-class of DataGridView and add the event handlers, but I'm having trouble.
Specifically, how can I override the onDragDrop event, when the only event intellisense sees does not have the correct signature.
I see a signature like: protected override void OnDragDrop(DragEventArgs e)
, but I'm expecting a signature like protected override void OnDragDrop(object sender, DragEventArgs e)
, because I'm using sender in my code. What am I missing? How should I properly override this event? My non-working code is below:
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);
}
}
}
}
You are making mistake in definition between events and delegates:
protected override void OnDragEnter(DragEventArgs e) { }
is a method which invokes the event DragEnter
of your datagrid.
And when this event accurs, all the delegates with signature protected override void OnDragEnter(object sender, DragEventArgs e) { }
are invoked.
So you can't override the event - this is just a field. You can override method which invokes it, but I think this is not that you are seeking for. I suggest you to add a handler for the DragEnter
event for your script during your constructor:
private DragGrid(DataTable table)
{
this.DataSource = table;
this.DragEnter += new DragEventHandler(_onDragEnter);
}
private void _onDragEnter(object sender, DragEventArgs e)
{
// your code here
}
The override is within the DataGridView itself. Simply replace 'sender' with 'this' and you will be all set.
精彩评论