Mega Code Archive

 
Categories / Delphi / Strings
 

Whats the delphi equivalent of visual basic control arrays

There isn't one. Delphi components do not have an Index property like VB controls, so you can't declare an array of them. However, there are three main reasons why you might want to, and each of them can be done in Delphi. Here's how: Reason 1. You want to share event handlers between different controls on a form. This is really easy. All you have to do is select the same event handler procedure in each of the controls' events. This is better than control arrays because you can even have the same event handler function across different kinds of control; for example, a toolbar button and a menu item can call the same function directly in each of their Click events. Reason 2. You want to be able to dynamically allocate and deallocate controls at run-time. This is also pretty easy in Delphi. Suppose you have a button on a form, and each time it is clicked, you want to create another, different button. The following sample code shows how to do this: procedure TForm1.Button1Click(Sender: TObject); var NewButton: TButton; begin NewButton := TButton.Create(Self); NewButton.Parent := Self; end; It is important to note that once this event finishes, the NewButton variable goes out of scope and we no longer have a pointer to the newly- created control. You can't deallocate a control within its own event handlers, so if at some point you want to remove one or more dynamically- created controls, you have to search for them in the Form.Controls array and/or maintain your own list of pointers to the controls you create. Assuming that there are no control event handlers running, it is safe to deallocate a control by just calling its Free method. Reason 3. You really want to access controls by number. I ran across this when I decided to write a board game similar to Reversi as a Delphi learning project. I had 100 TShape controls on a form, in a 10x10 grid. So, I painted all the shapes in the form designer and allowed it to give them names like "ShapeNN", but then I also declared an array of pointers to controls: "Board: array[1..10, 1..10] of ^TShape;" and populated it in the form's Create event. This is a hundred lines of code that really shouldn't be necessary, but from then on I could access controls in a two-dimensional array, like this: "Board[3,5]^.Brush.Color := clRed;" -- which is more than I could have done with VB.