简体   繁体   中英

Alternate color of groups of rows on a DBGrid

I want to alternate the colours of my grid by groups. My first try is doing this adding a GroupNumber to the ClientDataset (using the DENSE_RANK() function of SQL Server).

select dense_rank() over (order by Viatge) as GroupNumber, 
       Transports_v.* 
from Transports_v
where IdTransportista = :Id
order by 1

Now I can alternate colors on the grid using this code:

procedure TFFacturesTransportista.AEDBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
  if Odd(QAlbaransPEndentsGroupNumber.Value) then AEDBGrid1.Canvas.Brush.Color := clInfoBk;

  AEDBGrid1.DefaultDrawColumnCell(Rect,DataCol,Column,state);
end;

It works well, but if I manually delete a row then I can have two consecutive even or odd groups, and they will be drawn with the same colour.

Is there a better way to check if the current record starts a new group?.

Thank you.

There is no 'magic' function for what you want: use alternate color based on some field value (aka group) when the list is sorted on that field value/group.

But you could make your own list of groups (based on the dataset content) and then use the even/odd specification of the index of the group in that list to get the color.

When you delete rows, check to see if its the last row for that group and then delete the group from the list. Other way around, when a record is added with a new group, add the new group to the group list.

Small note: the order of the groups in the list must be the same as the order in which the groups appear in the dataset!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM