设置属性gridView1.OptionsSelection.EnableAppearanceFocusedCell = false; //确保选定行的背景色一样。
private BindingList<T> DataSource;
//dvginfo根据鼠标点击的x、y坐标获取该点的相关信息
private GridHitInfo downHitInfo;
private GridHitInfo upHitInfo; private void frmToExcelModel_Load(object sender, EventArgs e)
{
Init();
dvginfo.AllowDrop = true; // 确保能够拖拽
DataSource = new BindingList<T>();
dvginfo.DataSource =DataSource;
}
private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
{
e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
if (e.Info.IsRowIndicator)
{
if (e.RowHandle >= )
{
e.Info.DisplayText = (e.RowHandle + ).ToString();
}
else if (e.RowHandle < && e.RowHandle > -)
{
e.Info.Appearance.BackColor = System.Drawing.Color.AntiqueWhite;
e.Info.DisplayText = "G" + e.RowHandle.ToString();
}
}
}
#region 数据源拖拽
private void dvginfo_MouseDown(object sender, MouseEventArgs e)
{
downHitInfo = gridView1.CalcHitInfo(new Point(e.X, e.Y));
} private void dvginfo_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button != MouseButtons.Left) return; //判断是否是左键
if (downHitInfo == null || downHitInfo.RowHandle < ) return; //判断按下的位置是否有值,是否是gridview 的Items.
int[] rows = gridView1.GetSelectedRows();
List<ColunmData> linemodels = new List<ColunmData>();
foreach (int r in rows) // 获取gridview 数据源中对应的信息。
{
//根据 gridview 中的行索引获取数据源中对应的是行索引
int dataSourcerows = gridView1.GetDataSourceRowIndex(r);
linemodels.Add(DataSouse[dataSourcerows]);
}
dvginfo.DoDragDrop(linemodels, DragDropEffects.Move);//开始拖放操作。 }
//拖拽过程事件
private void dvginfo_DragOver(object sender, DragEventArgs e)
{
e.Effect = DragDropEffects.Move;
}
//拖拽完成后事件
private void dvginfo_DragDrop(object sender, DragEventArgs e)
{
//获取鼠标在屏幕上的位置。
Point gridviewPoint = this.PointToScreen(this.dvginfo.Location);
//获取 gridview 中对应的的位置(屏幕位置减去 gridView 开始位置)
upHitInfo = gridView1.CalcHitInfo(new Point(e.X - gridviewPoint.X, e.Y - gridviewPoint.Y));
if (upHitInfo == null || upHitInfo.RowHandle < ) return;
//获取释放的位置列索引
int endRow = gridView1.GetDataSourceRowIndex(gridView1.GetDataSourceRowIndex(upHitInfo.RowHandle));
List<ColunmData> row = e.Data.GetData(typeof(List<ColunmData>)) as List<ColunmData>; //获取要移动的数据
if (row != null && row.Count > ) //没有移动的数据跳过
{
int a;
//获取移动列集合的第一列在数据源的索引
int startRow = DataSouse.IndexOf(row[]);
ColunmData xs = DataSouse[endRow];
if (!row.Contains(xs)) //如果多选的话,确保不能拖拽到这几个里
{
gridView1.ClearSelection();
//排序,先删除后后添加,
for (int i = ; i < row.Count; i++)
DataSouse.Remove(row[i]);
//若果往上托,则加在鼠标到达行的上面
//如果往下拖,则加在鼠标到达行的下面
if (startRow > endRow)
a = DataSouse.IndexOf(xs);
else
a = DataSouse.IndexOf(xs) + ;
for (int i = ; i < row.Count; i++)
{
DataSouse.Insert(a + i, row[i]);
gridView1.SelectRow(a + i);
}
gridView1.FocusedRowHandle = a;
}
}
dvginfo.DataSource = DataSouse;
gridView1.RefreshData();
}
#endregion