基本逻辑
private GridHitInfo gridHitInfo = null;
private Point prePoint = new Point();
private void gridView_Main_MouseDown(object sender, MouseEventArgs e)
{
gridHitInfo = null;
var hitInfo = gridView_Main.CalcHitInfo(new Point(e.X, e.Y));
if (e.Button == MouseButtons.Left && hitInfo.InRow && hitInfo.RowHandle != GridControl.NewItemRowHandle)
{
gridHitInfo = hitInfo;
prePoint = new Point(e.X, e.Y);
}
}
private void gridView_Main_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left || gridHitInfo == null)
return;
var dragSize = SystemInformation.DragSize;
var dragRec = new Rectangle(new Point(gridHitInfo.HitPoint.X - dragSize.Width / 2, gridHitInfo.HitPoint.Y - dragSize.Height / 2), dragSize);
if (!dragRec.Contains(new Point(e.X, e.Y)))
{
gridView_Main.GridControl.DoDragDrop(gridHitInfo, DragDropEffects.Move);
gridHitInfo = null;
foreach (DataRow eachRow in dtMain.Rows)
{
eachRow["序号"] = dtMain.Rows.IndexOf(eachRow) + 1;
}
}
}
private void gridControl_Main_DragOver(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(GridHitInfo)))
{
var downHitInfo = e.Data.GetData(typeof(GridHitInfo)) as GridHitInfo;
if (downHitInfo == null)
{
return;
}
var hitInfo = gridView_Main.CalcHitInfo(gridControl_Main.PointToClient(new Point(e.X, e.Y)));
if (hitInfo.InRow && hitInfo.RowHandle != downHitInfo.RowHandle && hitInfo.RowHandle != GridControl.NewItemRowHandle)
e.Effect = DragDropEffects.Move;
else
e.Effect = DragDropEffects.None;
}
}
private void gridControl_Main_DragDrop(object sender, DragEventArgs e)
{
GridHitInfo srcHitInfo = e.Data.GetData(typeof(GridHitInfo)) as GridHitInfo;
GridHitInfo hitInfo = gridView_Main.CalcHitInfo(gridControl_Main.PointToClient(new Point(e.X, e.Y)));
var curPoint = gridControl_Main.PointToClient(new Point(e.X, e.Y));
var dy = curPoint.Y - prePoint.Y;
MoveRow(srcHitInfo.RowHandle, hitInfo.RowHandle);
}
private void MoveRow(int sourceRowHandle, int targetRowHandle)
{
if (sourceRowHandle == targetRowHandle)
return;
DataRow targetRow = gridView_Main.GetDataRow(targetRowHandle);
DataRow sourceRow = gridView_Main.GetDataRow(sourceRowHandle);
object[] objArray = sourceRow.ItemArray;
var dragRowCopy = dtMain.NewRow();
dragRowCopy.ItemArray = objArray;
sourceRow.Delete();
dtMain.Rows.InsertAt(dragRowCopy, targetRowHandle);
gridView_Main.FocusedRowHandle = targetRowHandle;
}
- 以上省去了一些步骤,只允许是在控件格内移动而不可以拖动到外面,如果需要的话,可以使用
prePoint
跟现在的点的坐标对比,算出水平和竖直的差是正还是负。