Delphi Tips : Displaying Image in DBGrid Columns

Sunday, July 13, 2008

In this tutorial I will share tips about how to displaying image in the DBGrid columns. You can use this method to mark rows that meet certain conditions matching with the conditions you specified. The components which I use is a TDBGrid, a TDatasource, and it is of course a TADOTable which is connected to a table in a Microsoft Access database. Set each of the component properties so that the components is connected to each other.





The following example show how images is used to mark the records base on value on the UnitsInStock column.


condition :

the product which its UnitsInStock value greater or equal to 10 is marked with a checklist image (checklist.bmp) and product which its UnitsInStock less than 10 is marked with a warning image (warning.bmp).



The Code


procedure TForm1.DBGrid1DrawColumnCell
(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn;
State: TGridDrawState);

var
Image : TBitMap;
begin
Image := TBitmap.Create;

try
with Image do begin
Transparent := True;
TransParentColor := Image.Canvas.Brush.Color;
TransparentMode := tmAuto;
end;

{ Image will only displayed if the table is not empty }
if DataSource1.DataSet.RecNo > 0 then
begin
if Column.Title.Caption = 'Stock OK' then
begin
{ if the quantity > 10 }
if (ADOTable1.FieldValues['unitsinstock'] > 10) then
begin
Image.LoadFromFile
(ExtractFilePath(Application.ExeName)+'\good.bmp');
DBGrid1.Canvas.Draw(rect.Left + 2,Rect.Top,Image);
end;

{ if the quantity > 0 and <= 10 }
if (ADOTable1.FieldValues['unitsinstock'] > 0)
and (ADOTable1.FieldValues['unitsinstock'] <= 10) then
begin
Image.LoadFromFile
(ExtractFilePath(Application.ExeName)+'\warning.bmp');
DBGrid1.Canvas.Draw(rect.Left + 2,Rect.Top,Image);
end;

end;
end;

finally
Image.Free;
end;

end;






You can download the source code here

0 comments:

Recent Comments

Tags Cloud

Blogumulus by Roy Tanck and Amanda Fazani