在原生控件DataGridView中實現(xiàn)仿Excel單元格下拉復制,;其實這個功能實現(xiàn)起來也比較簡單,,但是卻可以大大提高使用效率以及客戶體驗,。所以還是有必要加一下的,。 開發(fā)環(huán)境:.NET Framework版本:4.8 開發(fā)工具:Visual Studio 2022 實現(xiàn)這個功能,,其實只需要使用三個事件即可(鼠標按下,、移動、抬起) 由于DataGridView 提供了單元格內(nèi)的鼠標事件,,所以我們可以直接采用OnCellMouse 事件進行相關處理 鼠標按下事件,,判斷點擊的位置并且將要復制的單元格拿出來
protected override void OnCellMouseDown(DataGridViewCellMouseEventArgs e) { base.OnCellMouseDown(e); if (e.Button == MouseButtons.Left && Cursor == Cursors.Cross && copyModel == null) { if (e.RowIndex >= 0 && e.ColumnIndex >= 0) { Rectangle rect = GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false); if (e.X > rect.Width - 10 && e.Y > rect.Height - 10) { copyModel = new CopyModel { Value = Convert.ToString(Rows[e.RowIndex].Cells[e.ColumnIndex].Value), RowIndex = e.RowIndex, ColumnIndex = e.ColumnIndex }; } } }
}
鼠標移動事件,兩個作用,,一是改變鼠標狀態(tài),,二是跟隨移動賦值
protected override void OnCellMouseMove(DataGridViewCellMouseEventArgs e) { base.OnCellMouseMove(e); if (copyModel != null) { BeginInvoke(new Action(() => { if (e.RowIndex > copyModel.RowIndex) { Rows[e.RowIndex].Cells[copyModel.ColumnIndex].Value = copyModel.Value; Cursor = Cursors.Cross; return; } }));
} else { if (e.RowIndex >= 0 && e.ColumnIndex >= 0) { Rectangle rect = GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, false); if (e.X > rect.Width - 10 && e.Y > rect.Height - 10) { Cursor = Cursors.Cross; return; } } } Cursor = Cursors.Default; }
鼠標抬起事件,取消復制狀態(tài),,數(shù)據(jù)還原
protected override void OnCellMouseUp(DataGridViewCellMouseEventArgs e) { base.OnCellMouseUp(e); if (copyModel != null) { copyModel = null; Cursor = Cursors.Default; } }
???點擊此處下載源碼???
|