peiman F.
peiman F.

Reputation: 1658

change runtime created element style

i have 5 element those created at run time like these

NewButton := TImageViewer.Create(Self);
    with NewButton do
    begin
      Parent := Self;
      Bitmap.LoadFromStream(InStream);
      Height := 80;
      Width := 80;
      tag:=leftx;
      Position.X := leftx;
      Position.Y := 5;
      OnClick := WaitingButtonsClick;
      Enabled := True;
      Visible := True;
      Name := 'but' + IntToStr(leftx);
    end;
leftx := leftx+85;

so elements have their own name and tag

now after user clicked the image i have to change the loaded image

so i got the name on element after click

procedure TForm1.WaitingButtonsClick(Sender: TObject);
begin
// ShowMessage( (Sender as TAction).ActionComponent.Name );
   ShowMessage(TImageViewer(Sender).Name);
 // id := TButton(Sender).tag;
 // showmessage('slm'+id.ToString);
end;

ok.after getting the name of element how can i change the target file or style!?

Upvotes: 0

Views: 177

Answers (1)

quasoft
quasoft

Reputation: 5438

It seems that you are casting an object of type TImageViewer to TButton.

Change your click handler like that:

procedure TForm1.WaitingButtonsClick(Sender: TObject);
var 
  viewer: TImageViewer;
begin
  viewer := Sender as TImageViewer;

  // Change file or style of viewer
  //viewer.Bitmap.LoadFromFile(....);

  ...
end;

As a rule, always cast objects with as operator:

viewer := Sender as TImageViewer - RIGHT

vs

viewer := TImageViewer(Sender) - WRONG

The benefit is that as operator performs safety checks for you, and warns you if you are trying to cast to incompatible type.

The second variant can only be used if the variable is plain pointer (not an object), and that is rarely required.


Also using position on form to make component names unique is not recommended.

Its better to come up with another scheme for component name creation.

For example, you can define a counter in the form and add that counter to the names of the components.

Upvotes: 2

Related Questions