1

When dgRowSelect = False how can i detect the selected row within the OnDrawColumnCell method?

Not the selected cell, but the row that contains the selected cell.

srayner
  • 1,799
  • 4
  • 23
  • 39

1 Answers1

8

The code below seems to work. The TDBGrid still keeps SelectedRows updated (even though it doesn't draw with them without dgRowSelect enabled), so you can still access them in your drawing code. (You do still need to enable dgMultiSelect, even though dgRowSelect is not needed.)

The code lets the grid do all of the drawing, just setting the Canvas.Brush.Color on the selected rows. The supplied color will be overridden by the drawing code for a single cell if the state of that cell happens to be gdSelected.

I've set the color of the selected rows to clFuchsia, and left just the selected cell the default color for clarity (the grid is ugly with clFuchsia selected rows, but it works to demonstrate):

procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer;
  Column: TColumn; State: TGridDrawState);
var
  Selected: Boolean;
  Grid: TDBGrid;
begin
  Grid := TDBGrid(Sender); 
  if not (gdSelected in State) then
  begin
    Selected := Grid.SelectedRows.CurrentRowSelected;
    if Selected then
      Grid.Canvas.Brush.Color := clFuchsia;
  end;
  Grid.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;

Sample results of above, with the first and third rows selected:

enter image description here

You can, of course, just use the usual selected color of clHighLight; I found it to be confusing, though, because the current cell of an unselected row matched the color of the selected rows exactly. If they're directly next to each other, it was visually annoying.

Ken White
  • 123,280
  • 14
  • 225
  • 444
  • I can't test until I get back to my Delphi machine, but your answer looks good. Thanks. – srayner Dec 11 '12 at 22:06
  • 5
    @Ken, Thanks for choosing that fuchsia! Your screenshot really woke me up from almost sleeping state :-) [+1ed] – TLama Dec 12 '12 at 02:26
  • 1
    @TLama: Yeah, that was my intent. I was just writing the code, had a typo at `:= clF` when Code Insight popped up, and I thought "What the heck? It'll be clear, anyway." and hit Enter. When I ran it (and grabbed the screen cap), it really was clear what the effect of the code was, and I decided to leave it. ;-) – Ken White Dec 12 '12 at 02:34
  • 1
    I've accepted this answer as answering the question asked, but it still doesn't quite give me what i want. This solution has two problems. 1. when the grid is inially drawn the whole row is not highlighted. 2. If you click in a cell the whole row does highlight, but if you scroll away the highlight does not move to the newly selected row/cell. – srayner Dec 12 '12 at 16:31