Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top