During a recent project I was involved in, I had to implement a transparent row selection for the DataGridView control in a Winforms C# 2.0 application. This meant that instead of getting the usual dark blue color (SystemColors.Highlight) for each cell of the selected row to paint only a certain cell as dark blue and a dark blue border around the visible part of the row, the rest of the cells having to keep their already set colors.
The first thing that we need to take care in the grid view control in case we want to have a row selection is to set the SelectionMode property of the grid control to FullRowSelect. This will make sure that each time we select one cell, the entire row will be selected.
Once we complete this step we should start working on the actual “transparent” selection. In order to customize the look of the cells we need to implement the CellFormatting event of the DataGridView control and to change the way the cell looks when it’s selected we can customize two properties: SelectionBackColor (to change the background color of the cell in the selected state) and SelectionForeColor (to handle the color of the text in the cell in the selected state).
In order to have the first cell selected normally and the rest of the cells in the row to have the “transparent” selection look I used the following code for the CellFormatting event:
If we run the application after this step well get something like the following screenshot:
This looks fine, but it’s not enough – this looks like we would have cell level selection allowed only for the first column. This would look much better if we would paint a border around the selected row, to make it clear which row is selected and what type of selection mode we have. To achieve this I implemented the RowPostPaint event and used the following piece of code to draw a rectangle around my selected row:
Once we implement this event for our grid view we’ll reach the result we wanted:
This way of selecting a row in a DataGridView control can be very useful in case in the CellFormatting event we implement some logic to paint certain cell in some specific way based on some business logic. For example a red background for a cell in case of an error for that grid entry and so on… Such formatting would not be visible in case of the row beiong selected and we having left the default row selection implementation.
Implementing such a selection is not a very difficult task, but if you are not very familiar with the DataGridView control it can be tricky to know where and how to implement this. Hope this short article will be useful for other people as well.