Description:
How to implement block selection for XtraGrid cells?
Answer:
XtraGrid v6.1 and higher provides the built-in block (cell) selection. Please set the GridView.OptionsSelection.MultiSelectMode property to CellSelect. The additional information can be found in the XtraGrid's documentation:
Selections Overview
If you are using XtraGrid v2 or v3, you can implement this feature programmatically. There are two ways:
- Create a GridView descendant class with new functionality.
- Create a new (helper) class, which maintains a GridView instance and utilizes its events.
The second solution is the best, if the block selection feature should be added to existing grids without major changes to an existing project. This solution allows a programmer to achieve the desired effect with a minimum of code. It is also easy to use the helper class in many places of your project, i.e. reuse the same code.
Below is the description of how the BlockSelector helper class works. The following code creates a BlockSelector instance. No more code is needed to add the block selection feature to a grid view:
C#private BlockSelector blockSelector;
...
blockSelector = new BlockSelector(gridView1);
Visual BasicPrivate blockSelector As BlockSelector
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
...
blockSelector = New BlockSelector(GridView1)
End Sub
The BlockSelector class does not use the row selection feature of the XtraGrid in any way. Selected cells are maintained in a separate class (Block). A selected block is determined by the coordinates of two cells (top left and bottom right). A cell's coordinates are a row handle and a visible columns index.
BlockSelector uses the following events of the GridView class:
RowCellStyle –- visualizes "selection" by applying the SelectedRow style to cells which belong to the "selected" block.
MouseMove –- obtains a grid cell at the mouse cursor position and updates the selection block, if the left mouse button is pressed.
FocusedColumnChanged and FocusedRowChanged –- are used to "select" cells via the keyboard or the Shift+mouse click. The block is updated only if the Shift key is pressed.
The attached project includes the source code of the BlockSelector class. The code is quite simple and should be self explainatory.
The sample also demonstrates how to copy selected cells to the clipboard.
See Also:
How to obtain the text of selected rows and copy it to the clipboard
How to Select Rows via the Mouse
How to implement a Copy/Paste feature