Search code examples
delphivcl

delphi : Assign an image by its own name from the database


I want to select the image that will be displayed by its name in the database table. Note that the images are in PngImageList1 and have the same name. Can I replace the index and put the name instead? Please help.

procedure TForm3.FormCreate(Sender: TObject);
   var
cartRow: TFrm;
posX,posY : SmallInt;
P : TPanel ;
IMG : TImage;
larn : TLabel;
larc : TLabel;
lari : TLabel;
larfd : TLabel;
imgname,path:string;
begin
ScrollBox1.DestroyComponents;
posX := 0;
posY := 0;
imgname := FDQuery1.FieldByName('ImagePath').AsString;
FDQuery1.First;
while not FDQuery1.Eof do
  begin
    cartRow := TFrm.Create(ScrollBox1);
    cartRow.Parent := ScrollBox1;
    cartRow.Name := '';
    cartRow.Left := posX - 1;
    cartRow.Top := posY - 1;
    cartRow.Label1.Caption := FDQuery1.FieldByName('CountryAr').AsString;
    cartRow.Label2.Caption := FDQuery1.FieldByName('CountryID').AsString;
    PngImageList1.GetBitmap(imgname, cartRow.CIMG.Picture.Bitmap);
    cartRow.Width := ScrollBox1.Width;
    posY := posY + cartRow.Height + 1;
    FDQuery1.Next;
  end;

Database table:

Database table

PngImageList1:

PngImageList1


Solution

  • The latest version of TPngImageList introduces a function IndexByName: PngComponents

    In case you cannot or don't want to update, you can implement a similar function in your code based on the original sources:

    function TPngImageList.FindIndexByName(const AName: string): Integer;
    var
      I: Integer;
    begin
      Result := -1;
      for I := 0 to PngImages.Count - 1 do begin
        if SameText(PngImages[I].Name, AName) then begin
          Result := I;
          Break;
        end;
      end;
    end;