Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Arrays of Controls?

Status
Not open for further replies.

HighFrequency

Programmer
Jul 4, 2006
3
CA
Ok I'm kinda new to the GUI programming world. I have a bunch of button controls and shape controls (to simulate LEDs). I would like to be able to access them with some modular code. Is there a way I can name them like an array, so I can access them via a loop control variable for instance?
 
There is an easy way to store them in one place, just create a TList component:

Code:
TList* list = new TList();
//if you want to add, for example, a Tbutton and a TMemo:

list->Add(Button);
list->Add(Memo);

However, the problem is retrieving the pointers from the array, since the list->Items[] returns an general pointer (void* ), this is were you have to use DOWNCASTING;

For example, if you now that the array can hold ONLY buttons or memos, you can use downcasting:

Code:
for(int i=0;i<list->Count;i++) // this is the loop
{
 TButton* a=dynamic_cast<TButton*>((TObject*)list->Item[i]);

 TMemo* b = dynamic_cast<TMemo*>((TObject*)list->Items[i]);

 if(a) // if it's not null the element is an TButton!!!
 {
  //place the code here for using the button
 }

 if(b) // if it's not null the element is an TMemo!!!
 {
  //place the code here for using the memo
 }
}

I am very sure there is an easier way, but this is how I used arrays, since you might not know the exact location of the controls in the array, not even the type of the controls!! Hope this helps.
 
That's perfect man! Thanks a lot. Each array will contain only 1 type of control.

One last thing though, would I create the TList in the TForm declaration?

Thanks again,

Mike.
 
You should place the declaration in the header of your project(usually main.h) and create it (with new) in the constructor of the form, but it doesn't matter that much where you create it...

If you KNOW that you have only one type of control than you don't need downcasting.

For example if your control is a button and you want to see the names of all the buttons(in a TMemo):

Code:
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
 list = new TList();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::FormCreate(TObject *Sender)
{
 list->Add(Button1);
 list->Add(Button2);
 for(int i=0;i<list->Count;i++)
 {
   TButton* a = (TButton*)list->Items[i];
   Memo1->Lines->Add(a->Caption);
 }

In the header of the file, just add "TList* list" in the private members of the form.Also drag on the screen 2 buttons and a memo.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top