如何更改在delphi中的字段上具有相同值的dbgrid行的颜色?

例如,所有具有相同老师的行

注意:这些行是分组的,并在 dbgrid 中一个接一个

提前致谢

最佳答案

您可以使用 DBGrids onDrawColumnCell 事件轻松实现这一点:

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;

但是,如果您不知道教师的姓名,那么您将不得不执行某种递归操作,这是我的实现:
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;

关于delphi - 在delphi中更改字段值上的DBGRID行颜色,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16800103/

10-09 09:33