How can I use a mouse to select cell ranges in my datagrid
The Windows Forms DataGrid does not support the selection of a range of cells other than a group of rows. To select a row, you can click on its row header. But if you want to select a rectangular group of cells, you cannot.
To add this support, you can catch the mousedown on a cell, and in mousemove, track whether the mouse is dragged with the button down to other cells. If so, draw a selection rectangle over this group of cells. The attached samples (C#
) show how this might be done. The drawing of the selection rectangle is done in an OnPaint override. The samples also try to handle autoscrolling as you hit a grid border so the selection process can continue for cells that are not currently visible. To make the selection rectangle look nicer, the code also hides the current cell when it draws a selection rectangle.
The samples have a derived DataGrid that has a public member, SelectedRange, that holds the TopLeft and BottomRight coordinates of the selected range. The derived grid also has a public event, SelectionChanging, that fires prior to the selection changing as you drag your mouse. The event passes both the old selection and the new selection, and allows you to cancel the action if you choose.