我在一个项目中遇到了这个确切的问题——如何允许用户使用标准方法在 datagridview 中选择一堆行,然后将选择拖到另一个 datagrid 视图中并删除它。我能够从http://www.codeproject.com/Tips/338594/Drag-drop-multiple-selected-rows-of-datagridview-w建立一个想法,这只是将 DataGridView 子类化为“可拖动” DataGridView,当用户在已选择的行上按下按钮时捕获鼠标操作,同时允许所有其他情况的标准行为:
public partial class DraggableDataGridView : System.Windows.Forms.DataGridView {
private Rectangle dragBoxFromMouseDown;
protected override void OnMouseDown(MouseEventArgs e) {
// Trap the case where the user pressed the left mouse button on an already-selected row
// without <shift> or <control>
if ((e.Button & MouseButtons.Left) == MouseButtons.Left
&& Control.ModifierKeys == Keys.None
&& this.SelectedRows.Count > 0
&& HitTest(e.X, e.Y).RowIndex >= 0
&& this.SelectedRows.Contains(this.Rows[HitTest(e.X, e.Y).RowIndex])
) {
// User pressed the mouse button over an already-selected row without <shift> or <control> so we should
// consider drag and drop. Record a rectangle around that mouse location to possibly trigger drag
// operation
Debug.WriteLine("MouseDown inside selection");
Size dragSize = SystemInformation.DragSize;
dragBoxFromMouseDown = new Rectangle(new Point(e.X - (dragSize.Width / 2), e.Y - (dragSize.Height / 2)), dragSize);
} else {
// In other cases use the default behavior for datagridview
Debug.WriteLine("MouseDown outside selection");
dragBoxFromMouseDown = Rectangle.Empty;
base.OnMouseDown(e);
}
}
protected override void OnMouseUp(MouseEventArgs e) {
base.OnMouseUp(e);
}
protected override void OnMouseMove(MouseEventArgs e) {
if ((e.Button & MouseButtons.Left) == MouseButtons.Left) {
// If the mouse moves outside the drag limit rectangle, start the drag.
if (dragBoxFromMouseDown != Rectangle.Empty && !dragBoxFromMouseDown.Contains(e.Location)) {
// Proceed with the drag and drop, passing in the selected rows
DragDropEffects dropEffect =
this.DoDragDrop(this.SelectedRows, DragDropEffects.Move);
}
}
base.OnMouseMove(e);
}
public DraggableDataGridView() {
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs pe) {
base.OnPaint(pe);
}
}
有了这段代码,然后用这个自定义组件替换我在表单中的所有 DataGridView,我可以将它们用作标准拖动源,并以通常的方式将它们“插入”到其他组件的标准拖放功能中。