Change DBGRID row color on field value in delphi
Asked Answered
B

1

5

How to change color of dbgrid rows that have the same value on a field in delphi?

for example all rows that have the same teacher

note: those rows are grouped, and come after each other in dbgrid

thanks in advance

Byblow answered 28/5, 2013 at 19:40 Comment(0)
O
19

You can easily implement this using the DBGrids onDrawColumnCell Event :

procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
  DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
 if Table1.FieldByName('Teacher').AsString = 'Joe'
 then
  DBGrid1.Canvas.Brush.Color:=clRed;
 DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State);  

end;

However, if you do not know the name of the Teachers then you will have to implement some sort of recursive action, this is my implementation :

var TeacherStringList : TStringList;
    lastColorUsed : TColor;
    AColors : Array of TColor;


function mycolor: TColor;
begin
  result := RGB(Random(256), Random(256), Random(256));
end;

procedure TForm3.Button1Click(Sender: TObject);
var CurrS : String;
    Index : Integer;
begin

  if TeacherStringList.Count <> 0 then TeacherStringList.Clear;
  Table1.DisableControls;
  try
    while not Table1.Eof do
    begin

      CurrS := Table1.FieldByName('Teacher').AsString;
      if (not TeacherStringList.Find(CurrS,Index)) and (not currS.IsEmpty)
      then  TeacherStringList.Add(CurrS);
      Table1.Next;

    end;
    Table1.First;
    SetLength(AColors,TeacherStringList.Count);
    for Index := Low(AColors) to High(AColors)
    do AColors[Index] := mycolor;

  finally
    Table1.EnableControls;
  end;

end;

procedure TForm3.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
  DataCol: Integer; Column: TColumn; State: TGridDrawState);
var Index : integer;

begin

  if (TeacherStringList.Find(Table1.FieldByName('Teacher').AsString,Index))
  then 
    DBGrid1.Canvas.Brush.Color:= AColors[index];

  DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State);

end;

procedure TForm3.FormCreate(Sender: TObject);
begin
  teacherStringList := TStringList.Create;
  teacherStringList.Sorted := True;
end;

procedure TForm3.FormDestroy(Sender: TObject);
begin
  teacherStringList.Free;
end;
Overdevelop answered 28/5, 2013 at 20:3 Comment(2)
Suppose : Table1.FieldByName('Teacher').AsString = 'Joe' in first 10 rows; Table1.FieldByName('Teacher').AsString = 'Jack' in next 5 rows; Table1.FieldByName('Teacher').AsString = 'Jim' in next 8 rows; I need first 10 rows be gray, next 5 rows be white and next 8 rows be gray and next again whiteByblow
Please next time do note that in the question, It's important that you provide as much data when possible, Updated my answer.Overdevelop

© 2022 - 2024 — McMap. All rights reserved.