【问题标题】:Change DBGRID row color on field value in delphi在delphi中更改字段值的DBGRID行颜色
【发布时间】:2013-05-29 21:52:41
【问题描述】:

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

例如具有相同教师的所有行

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

提前致谢

【问题讨论】:

    标签: delphi colors dbgrid tdbgrid


    【解决方案1】:

    您可以使用 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;
    

    【讨论】:

    • 假设:Table1.FieldByName('Teacher').AsString = 'Joe' 在前 10 行; Table1.FieldByName('Teacher').AsString = 'Jack' 在接下来的 5 行; Table1.FieldByName('Teacher').AsString = 'Jim' 在接下来的 8 行中;我需要前 10 行是灰色的,接下来的 5 行是白色的,接下来的 8 行是灰色的,接下来是白色的
    • 请下次注意问题中,尽可能提供尽可能多的数据很重要,更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    相关资源
    最近更新 更多