My application uses a TButtonGroup control. I assign to each button an event handler: doClick. By assigning information to each button (Pointer (i)) I can figure out which button was called. This is the code:
procedure TVector_Menu.Synchronize (rows, cols: Int32);
var btn: TGrpButtonItem;
i: Int32;
begin
ButtonGroup.Items.Clear;
Self.Rows := rows;
Self.Cols := cols;
for i := 0 to rows * cols - 1 do
begin
btn := Buttongroup.Items.Add;
btn.Data := Pointer (i);
btn.ImageIndex := i;
btn.OnClick := doClick;
end; // for
Self.ClientHeight := 4 + rows * ButtonGroup.ButtonHeight;
Self.ClientWidth := 22 + cols * ButtonGroup.ButtonWidth;
end; // Synchronize //
procedure TVector_Menu.doClick (Sender: TObject);
var btn: TGrpButtonItem;
i, r, c: Int32;
begin
btn := (Sender as TGrpButtonItem); // @@@ TButtonGroup
i := Int32 (btn.Data);
get_rc (i, r, c);
if Assigned (FOnClick)
then FOnClick (Sender, @FButton_Matrix [r, c]);
end; // doClick //
When doClick is called I get an Invalid Typecast at the line labeled ‘@@@’. The typecast is correct when I use TButtonGroup for btn as well as in the typecast, but this one does not contain a data property and that would not have been of much use anyway.
As a Test I assigned an OnClick event handler to the TButtonGroup control and I noticed that when I click a button, first the button event handler is called and next the TButtonGroup, containing the button, event handler.
Question: is there a way to find out which button of a TButtonGroup was clicked?
Using Delphi XE on Windows 7/64
You get an invalid typecast exception because
Senderis in fact theTButtonGroupand is not aTGrpButtonItem. What this means is that you need to use a different event handler for each button if you are going to useTGrpButtonItem.OnClick.In your situation it is clear that you should use the
TButtonGroup.OnButtonClickedevent which does provide the button index.There is a potential pitfall here, however, that you need to make sure you avoid. The documentation states:
In other words the
OnButtonClickedevent will only fire if you have not assigned anOnClickevent handler for either the button group or the button item.