Grid control (DBGrid) is often used in DELPHI. Grid control only provides the color attributes of each row, but in actual applications, we often want it to display different colors according to the value of a certain row and item. , even display images in unit table items in the grid, etc. Let’s use a simple example to tell you how to do it.
For example, if there is a book refund in spring, it is represented by red, and if there is a book refund in autumn, it is represented by yellow (Figure 1)
Figure 1
Such requirements can be easily achieved using DBGrid self-drawing function. Users can handle DBGrid's OnDrawColumnCell event, where they achieve special effects. To determine whether the record meets the requirements, you can use the DataLink property of DBGrid to obtain data, but the DataLink property of DBGrid is a protected member and must be called in the subclass of TCustomDBGrid.
type TMyCustomDBGrid = class(TCustomDBGrid); procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState); varsCjts,sQjTs:String; began with TMyCustomerDBGrid(Sender) do begin Cjts :=DataLink.Fields[5].AsString; sQjts:=DataLink.Fields[9].AsString; if sCjts<>''' then //The number of spring return books>0 is displayed in red Canvas.Brush.Color: = clRed else if sQjts<>''' then //The number of autumn books returned>0 is displayed in yellow Canvas.Brush.Color := clYellow else Canvas.Brush.Color:=clWhite; Canvas.Font.Color:=clBlack ; canvas.fillrect(rect); canvas.textout(rect.left+4,rect.top+4,Column.Field.AsString); end; end; |
This method can extend various modification methods of other controls, such as different colors can be used according to the data item value, and different colors can be displayed according to the record number. In short, flexibly applying objects such as canvas, rect and bitmap can decorate various grids in a colorful way.