在delphi中更改字段值的DBGRID行颜色 [英] Change DBGRID row color on field value in delphi
本文介绍了在delphi中更改字段值的DBGRID行颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何更改在delphi中某个字段上具有相同值的dbgrid行的颜色?
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
注意:这些行被分组,并且在dbgrid中排在后面
note: those rows are grouped, and come after each other in dbgrid
预先感谢
推荐答案
您可以使用DBGrids onDrawColumnCell事件轻松实现此目的:
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;
这篇关于在delphi中更改字段值的DBGRID行颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文