利用DBGrid自绘功能可以很容易地实现这样的要求。用户可以处理DBGrid的 OnDrawColumnCell事件,在其中实现特殊的效果。在Delphi中,我们无须绘制所有单元,只需要绘制我们需要改变的单元,而调用 DefaultDrawColumnCell方法把其它单元的绘制工作交给Delphi去做,Delphi会绘制单元格,包括背景色、边框、焦点框、固定 单元格的三维效果。要判断记录是否满足要求,可以使用DBGrid的DataLink属性获得数据,但DBGrid的DataLink属性属于保护成员, 必须在TCustomDBGrid的子类中调用。下面是一个简单的改变某些行颜色的例子:
type
TMyCustomDBGrid = class(TCustomDBGrid);
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
var s: string;
begin
with TMyCustomDBGrid (Sender) do
begin
s := DataLink.Fields[1].AsString;
if s = '张三' then
Canvas.Brush.Color := clRed
else
Canvas.Brush.Color := clBlack;
DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
end;