ButtonClick fired only for last element

Hello,

I do not understand this behaviour:

I have a TWebListControl and add Items dynamically to it like this:

procedure TForm2.WebFormCreate(Sender: TObject);
begin
  WebListControl1.Items.Clear;
  for i := 1 to 3 do
  begin
    li := WebListControl1.Items.Add;
    li.Text := '<div class="row">' +
      '<div class="col-sm-2 col-status"><span class="badge rounded-pill bg-success status_badge">new</span></div>' +
      '<div class="col">' +
      '<h5>Heading</h5><small class="form-text">Help text for a form field.</small>' +
      '</div>' +
      format('<div class="col-sm-4 text-end"><button class="btn btn-link" id="btn-%d">bearbeiten</button></div>', [i]) +
      '</div>'
      ;
// this assigns the BtnClick-Handler only to the last element
    btn := TWebButton.Create('btn-' + i.ToString);
    btn.Tag := i;
    btn.OnClick := btnclick;
  end;
// this works as expected for all three elements
//  for i := 1 to 3 do
//  begin
//    btn := TWebButton.Create('btn-' + i.ToString);
//    btn.Tag := i;
//    btn.OnClick := btnclick;
//  end;
end;

Kind regards
Harald

It is because setting ListItem.Text will rerender the entire listcontrol to have it updated. Thus, the button HTML elements will be re-rendered and no longer be bound to btn except for the last that is created after which there is no re-rendering.
Recommended is to create all items within BeginUpdate/EndUpdate and after that, assign button controls.

1 Like