Determining the position of the control inside the TGridPanel

How can I find out the position (row and column index) of controls inside a TGridPanel? I would like to use a generic OnClick event for the number of buttons and know the X, Y position of the button.

I am using Delphi 2007.

+2


source to share


2 answers


Unfortunately, due to the magic of the TGridPanel, this is a little more complicated than just getting the Top and Left properties ...

This should do it for any control, adapt it to your needs:



procedure GetRowColumn(const AControl: TControl; var ARow, AColumn: Integer);
var
  I: Integer;
begin
  if AControl.Parent is TGridPanel then
  begin
    I := TGridPanel(AControl.Parent).ControlCollection.IndexOf(AControl);
    if I > -1 then
    begin
      ARow := TGridPanel(AControl.Parent).ControlCollection[I].Row;
      AColumn := TGridPanel(AControl.Parent).ControlCollection[I].Column;
    end;
  end;
end;

procedure TForm1.ButtonClick(Sender: TObject);
var
  Row, Column : Integer;
begin
  GetRowColumn(Sender as TControl, Row, Column);
  // do something with Row and Column
  ShowMessage( Format('row=%d - col=%d',[Row, Column]));
end;

      

+5


source


You can use Sender cast as a tButton and then request it from top and left, like so:

Procedure TForm1.OnClick(Sender:tObject);
var
  X,Y : Integer;
begin
  if Sender is TButton then
    begin
      X := TButton(Sender).Top;
      Y := TButton(Sender).Left;
      // do something with X & Y
    end;
end;

      

Or, if you just want to know which button was clicked, you can also use the TAG property to insert a number into each button, and then get the tag value in your onclick event. Just remember to set the Tag property for something first. You can do this in the form designer if you are just dropping the buttons in the grid bar or in the routine you use to create and insert your buttons.



Procedure TForm1.OnClick(Sender:tObject);
var
  iButton : integer;
begin
  if Sender is TComponent then
    begin
      iButton := TComponent(Sender).Tag;
      // do something with iButton
    end;
end;

      

You can also use a tag property to store more than just an integer, since a pointer currently uses the same memory size as an integer, which you can overlay a pointer to an integer and insert that value into a tag property. Just keep in mind that any pointer you place in this field is still treated as an integer. You are responsible for the memory it points to, it will not be managed by the component.

0


source







All Articles