Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

delphi - how to keep track of selected rows with dgRowSelect = False

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...