1

I am rendering the content of a database table in a TGrid, which works fine. Now I would like to show an image of a trash can on every row as a button to delete the row. How can this be done?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Maybe the answer to this question (https://stackoverflow.com/questions/24737325/how-can-i-insert-a-button-in-grid-cell-firemonkey-xe6) will help you? It explain how to add a button. You have to assign the trash can icon on the button. Let me know if it works for you. – fpiette Apr 17 '21 at 08:19

2 Answers2

2

There are several ways to paint an image in a Grid. In cases, where the images will be loaded at runtime e.g. from a database, I prefer to use the OnDrawColumnCell event:

procedure TForm1.Grid1DrawColumnCell(Sender: TObject; const Canvas: TCanvas;
  const Column: TColumn; const Bounds: TRectF; const Row: Integer;
  const Value: TValue; const State: TGridDrawStates);
var
  bmp: TBitmap;
begin
  if Column.Name = 'ImageColumn1' then
  begin
    bmp := ImageList1.Bitmap(Bounds.Size, Row mod ImageList1.Count);
    if assigned(bmp) then
    begin
      Grid1.BeginUpdate;
      Canvas.DrawBitmap(bmp, bmp.Bounds, Bounds, 1);
      Grid1.EndUpdate;
    end;
  end;
end;

This example expects an ImageList1 with several preloaded images. It draws all images into the column with the name ImageColumn1. To take your images from the database, replace the line with the bmp access.

Update at 18-Apr-21:

If you simply want to show a trash icon or e.g. a status icon, you can put an image list on the form. Add a TImageColumn or TGlyphColumn (e.g. as column number 2) and fill the image in this event into the cell:

procedure TForm1.Grid1GetValue(Sender: TObject; const ACol, ARow: Integer;
  var Value: TValue);
begin
  if ACol = 2 then
    Value := ImageList1.Bitmap(Bounds.Size, <NumberOfBitmapWithinImageList>);
end;

For a trash icon, you can write your delete action into the following event method:

procedure TForm1.Grid1CellClick(const Column: TColumn; const Row: Integer);
begin
  if Column = ImageColumn1 then
    ShowMessage('Row ' + Row.ToString + ' clicked');
end;
1

try this code on event onDrawColumnCell

if stgMain.Cells[0, Row] = 'isImage' then begin
  Bounds.Location := PointF(Bounds.Location.X, Bounds.Location.Y + ((Bounds.Height - Bounds.Width) / 2));

  Bounds.Width := Bounds.Width;
  Bounds.Height := Bounds.Width;

  Canvas.Fill.Kind := TBrushKind.Bitmap;
  Canvas.Fill.Bitmap.WrapMode := TWrapMode.TileStretch;

  Canvas.FillRect(Bounds, 0, 0, AllCorners, 1);

  Canvas.Fill.Bitmap.Bitmap := FMain.img.Bitmap(Bounds.Size, 2);
end;