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 Sender
is in fact the TButtonGroup
and is not a TGrpButtonItem
. What this means is that you need to use a different event handler for each button if you are going to use TGrpButtonItem.OnClick
.
In your situation it is clear that you should use the TButtonGroup.OnButtonClicked
event which does provide the button index.
There is a potential pitfall here, however, that you need to make sure you avoid. The documentation states:
Occurs when a button is clicked, if the OnClick event is not present.
In other words the OnButtonClicked
event will only fire if you have not assigned an OnClick
event handler for either the button group or the button item.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With