DevExpress GridView中将MultiSelect设为True后,禁用鼠标拖动选择多行的功能,而保留ctrl shift的多选功能
最近项目中遇到一个需求--拖动表格行进行排序,当把GridView中MultiSelect设为false时很正常,但把MultiSelect设为True后,拖动时会选中多行,经研究找到以下解决方法:
思路是重写**OnMouseMove、OnMouseUp**方法,**OnMouseMove重写时将MultiSelect设为False,OnMouseUp重写再将MultiSelect设为True**。
这样既不影响拖动效果(拖动排序时不会再选中多行),拖动排序完后,又能正常多选进行删除行等操作,完整代码如下:
public partial class DraggableGridControl : DevExpress.XtraGrid.GridControl { GridView gridView = null; Point m_mouseDownLocation; int m_dragHandle; DragForm m_dragRowShadow; bool multiSelectFlag = false; protected override void OnMouseDown(MouseEventArgs ev) { if (ev.Button == MouseButtons.Left) { if (gridView == null) { gridView = ((GridView)base.MainView); } var _hit = gridView.CalcHitInfo(ev.Location); if (_hit.RowHandle >= 0) { m_dragHandle = _hit.RowHandle; m_mouseDownLocation = ev.Location; } else { m_dragHandle = -1; } } base.OnMouseDown(ev); } protected override void OnMouseMove(MouseEventArgs ev) { if (ev.Button == MouseButtons.Left && m_dragHandle >= 0) { if (m_dragRowShadow == null) { double _x2 = Math.Pow((ev.Location.X - m_mouseDownLocation.X), 2); double _y2 = Math.Pow((ev.Location.Y - m_mouseDownLocation.Y), 2); double _d2 = Math.Sqrt(_x2 + _y2); if (_d2 > 3) { //执行拖拽; this.BeginDrag(m_dragHandle); } } else { m_dragRowShadow.Location = new Point(m_dragRowShadow.Location.X, this.PointToScreen(ev.Location).Y); } } base.OnMouseMove(ev); } protected override void OnMouseUp(MouseEventArgs ev) { if (m_dragRowShadow != null) { var _hit = gridView.CalcHitInfo(ev.Location); this.EndDrag(_hit.RowHandle); } base.OnMouseUp(ev); } private void BeginDrag(int _handle) { if (gridView.OptionsSelection.MultiSelect == true) { multiSelectFlag = true; gridView.OptionsSelection.MultiSelect = false; } var _info = (DevExpress.XtraGrid.Views.Grid.ViewInfo.GridViewInfo)gridView.GetViewInfo(); Rectangle _bound = _info.GetGridRowInfo(_handle).Bounds; _bound.Location = this.PointToScreen(_bound.Location); m_dragRowShadow = new DragForm(_bound); m_dragRowShadow.Show(); } private void EndDrag(int _handle) { if (m_dragRowShadow != null) { m_dragRowShadow.Close(); m_dragRowShadow.Dispose(); m_dragRowShadow = null; int _rowIndex = gridView.GetDataSourceRowIndex(m_dragHandle); DataRow _row = ((DataTable)this.DataSource).Rows[_rowIndex]; object[] _values = _row.ItemArray; base.BeginUpdate(); //移除目标行; ((DataTable)this.DataSource).Rows.RemoveAt(m_dragHandle); _row = ((DataTable)this.DataSource).NewRow(); _row.ItemArray = _values; if (_handle >= 0) { //插入指定位置; ((DataTable)this.DataSource).Rows.InsertAt(_row, _handle); gridView.FocusedRowHandle = _handle; } else { //添加; ((DataTable)this.DataSource).Rows.Add(_row); gridView.FocusedRowHandle = gridView.RowCount - 1; } base.EndUpdate(); if (multiSelectFlag) gridView.OptionsSelection.MultiSelect = true; } } }