Question

I have an array of PANELs on a form and they are used as buttons. There is one event procedure assigned to them. So when I click on a button, I can see it's caption like this:

procedure TForm1.MenuAction0Click(Sender: TObject);
begin
  TPanel(Sender).Font.Bold:= true;
  ShowMessage( TPanel(Sender).Caption);

end;

I want to know the button number (as in array element number) and not the caption. How is this possible?

Thanks!

Was it helpful?

Solution

Use the Tag property of the control. The Tag property is free to set to any integer that is useful to you, and it is not used by the control. So when you create each panel, set the Panel.Tag to the index in the array. Then you can get the index in the array by using TPanel(Sender).Tag

OTHER TIPS

If your button is in an array, it's because you put it in an array. The button has no inherent knowledge of the array, and neither does anything else in your program. To find the button in the array, search for it:

function GetButtonArrayIndex(const ButtonArray: array of TButton; Button: TButton): Integer;
begin
  for Result := 0 to High(ButtonArray) do
    if ButtonArray[Result] = Button then
      Exit;
  Result := -1;
end;

An alternative is to forego any direct manipulation of the array and just store the button's array index in its Tag property.

If you're using Tag for something else already, or you don't like how its name doesn't indicate its specific purpose in your program, you could instead use a TDictionary<TButton, Integer> to map buttons to array indices without having to search the array: just look up the index from the given button. And once you're using a TDictionary, you may be able to skip the array index and just map the button directly to whatever else it is that the array index was supposed to point to, such as a data structure that holds information related to the button.

iter: integer;

for iter := 0 to TPanel(Sender).Parent.ControlCount - 1 do
begin
  if Sender = TPanel(Sender).Parent.Controls[iter] then
  begin
    // number is iter
  end;
end;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top