Κυριακή 4 Μαρτίου 2012

Drawing an image in a cell of a Delphi DBGrid

Designed to enable a user to view and edit data in a tabular grid, the TDBGrid component provides various ways of customizing its appearance. With so flexible component, a Delphi developer can always find new ways to make data more attractive. 

A picture is worth a thousand words

While adding colors to a DBGrid can produce some neat effects, if you really want to improve the visual representation of data in you applications, you might consider using images instead of the "boring" text. 

Images in DBGrid
Let's see how to paint an image in a cell of a TDBGrid. 

Here's how the OnDrawColumnCell event handler for the DBGrid1 component looks:
procedure TForm1.DBGrid1DrawColumnCell(
  Sender: TObject;
  const Rect: TRect;
  DataCol: Integer;
  Column: TColumn;
  State: TGridDrawState);
var
  bitmap : TBitmap;
  fixRect : TRect;
  bmpWidth : integer;

  imgIndex : integer;
begin
  fixRect := Rect;

  // customizing the 'LastName' field
  if Column.Field = EmployeeTableLastName then
  begin
    //adding some logic to grab the required image
    if EmployeeTableSalary.Value > 50000 then
      imgIndex := 0
    else if EmployeeTableSalary.Value > 25000 then
      imgIndex := 1
    else
      imgIndex := 2;


    bitmap := TBitmap.Create;
    try
      //grab the image from the ImageList 
      //(using the "Salary" field's value)
      ImageList1.GetBitmap(imgIndex,bitmap);
      //Fix the bitmap dimensions
      bmpWidth := (Rect.Bottom - Rect.Top);
      fixRect.Right := Rect.Left + bmpWidth;
      //draw the bitmap
      DBGrid1.Canvas.StretchDraw(fixRect,bitmap);
    finally
      bitmap.Free;
    end;

    // reset the output rectangle, 
    // add space for the graphics
    fixRect := Rect;
    fixRect.Left := fixRect.Left + bmpWidth;
  end;

  //draw default text (fixed position)
  DBGrid1.DefaultDrawColumnCell(
     fixRect,
     DataCol,
     Column,
     State);
end;

To "paint" the above DBGrid, I've used a TImageList (ImageList1) component ("Win32" component palette tab) to store some (dummy for this test) images. Three images are added, each used to reflect the value of an employees salary.

Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου