views:

321

answers:

3

My DGV has row BackColors set to various colours based on business logic. When a user selects the row the colour changes to the selected row BackColor thus obscuring the pre-set colour. I would like to preserve the original colour when a row is selected and indicate selection with (perhaps) a bold border around the selected row. Is this possible? Is there an easy alternative I'm missing?

EDIT To make it clear, this is a WinForms app.

A: 

You can use

<SelectedRowStyle CssClass="MyCssClass" />

where you'd create a CSS class to define a table row with your required border style. Or you can use in-line border styling with

<SelectedRowStyle BorderStyle="Solid" BorderWidth="1" BorderColor="Black" />
mdresser
+3  A: 

In order to change the default behavior of the DataGridView you typically need to derive a child class based off the DataGridView class. I had to do this when I wanted to change the default behavior of the DataGridView's table cells as far as input goes, ie. pressing the up and down arrow, enter key, that sort of stuff.

What you're asking seems simliar to creating a custom column, I believe you should follow the same steps. However, I'm not sure how you could change the background color.

I would suggest you start there. In fact, when you want to do more with the datagridview than Microsoft intended, I've found you need to do this.

I would like to include a few links:

MSDN on creating custom columns for the DataGridView

Blog about creating custom input behavior for DataGridView

I know this may take some time and you were probably hoping for a quick fix, but learning the above can help you with other projects as well.

I may be wrong, there may be an easier way to do what you're saying.

Also, try googling "datagridview custom behavior".

I believe you are talking about a windows form application and not a web application, correct?

shady
+2  A: 

Another possibility is to set the selection color to be a darker shade of the normal back color. This would be much simpler than having to reimplement the drawing of borders of selected rows.

So when you add a row with, say, a yellow background

Dim backColor as Color = Color.Yellow
row.DefaultCellStyle.BackColor = backColor
row.DefaultCellStyle.SelectionBackColor = Color.FromArgb(backColor.R * 3 / 4, backColor.G * 3 / 4, backColor.B * 3 / 4)

Multiplying each color component by the same number < 1 serves to darken the color, you could play around with different values here to see what pleases you the most aesthetically.

Patrick McDonald
I didn't realise you could set the selection colour on an individual row. Problem solved!
Simon