Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to add an image on the selected field in a dbgrid in Delphi 7

sysmatics

IS-IT--Management
Apr 30, 2009
3
IN
I want to add an image to the selected field in a Delphi 7 dbgrid. The dbgrid displays many fields, and if the user selects a field, I have to add an image to its title.

Thanks,
Sridhar
 

Attachments

  • Screenshot (125).png
    Screenshot (125).png
    62.6 KB · Views: 4
try this:

procedure TForm1.DBGrid1DrawDataCell(Sender: TObject; const Rect: TRect;
Field: TField; State: TGridDrawState);
var
index: integer;
begin
//your conditional ....
if (Field.Tag = Field.Dataset.RecNo) and (Field = Table1Field1) then begin
//never mind the Rect we can draw where we like.
index:= 1;
// Rect = cell rectangle
ImageList1.Draw(DBGrdi1.Canvas, 2, Rect.Top, index, dsTransparent);
end
else { use default Draw... }
DBGrid1.DefaultDrawDataCell(Rect, Field, State);
end;
 
NOTE: in new IDE, like RAD 12...

Vcl.DBGrids.TDBGrid.OnDrawDataCell
Occurs when the grid needs to paint a cell if the State property of Columns is csDefault.
Do not write an OnDrawDataCell event handler. OnDrawDataCell is obsolete and included for backward compatibility. Instead, write an OnDrawColumnCell event handler.

1736618483567.png

Code:
var
  LBmp: TBitmap;

procedure TForm1.Button1Click(Sender: TObject);
begin
  DBGrid1.DefaultDrawing := not DBGrid1.DefaultDrawing;
  //
  if DBGrid1.DefaultDrawing then
    Caption := 'DBGrid1.DefaultDrawing = true'
  else
    Caption := 'DBGrid1.DefaultDrawing = false';
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  CountryTable.Active := not CountryTable.Active;
end;

procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
  if DataCol = 0 then
  begin
    Column.Color      := clBlue;
    Column.Font.Color := clYellow;
    //
    // ImageList1.Draw(DBGrid1.Canvas, 2, Rect.Top, 0, true);
    //
    if ImageList1.GetBitmap(10, LBmp) then
      DBGrid1.Canvas.Draw(Rect.Left, Rect.Top, LBmp);
    //
    DBGrid1.Canvas.TextOut(Rect.Left + LBmp.Width, Rect.Top, Column.Field.AsString);
  end
  else
    DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  LBmp := TBitmap.Create;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  LBmp.Free;
end;
 
Last edited:

Part and Inventory Search

Sponsor

Back
Top