I am using C++Builder and I have 64 TImage
controls with different Tag
values. Can I find an Image by its Tag somehow? I need this because my function has to move between two objects (which are Images) by adding 1 to their Tag
s. I am using the VCL library.
There is no function available in the VCL to do this for you. You will have to manually loop through the Components[]
property of the owning TForm
, or the Controls[]
property of the Parent
of the TImage
controls, checking each component/control for TImage
before accessing their Tag
, eg:
TImage* TMyForm::FindImageByTag(NativeInt ATag)
{
for(int i = 0; i < ComponentCount /* or: SomeParent->ControlCount */; ++i)
{
if (TImage *img = dynamic_cast<TImage*>(Components[i] /* or: SomeParent->Controls[i] */))
{
if (img->Tag == ATag)
return img;
}
}
return NULL;
}
TImage *img = FindImageByTag(...);
if (img)
img->Tag = img->Tag + 1;
Alternatively, you should store pointers to your TImage
controls in your own array, which you can then index into/loop through when needed, eg:
private:
TImage* Images[64];
...
__fastcall TMyForm::TMyForm(TComponent *Owner)
: TForm(Owner)
{
Images[0] = Image1;
Images[1] = Image2;
Images[2] = Image3;
...
Images[63] = Image64;
}
TImage* TMyForm::FindImageByTag(NativeInt ATag)
{
for(int i = 0; i < 64; ++i)
{
if (Images[i]->Tag == ATag)
return Images[i];
}
return NULL;
}
When populating the array, if you don't want to hard-code the 64 pointers individually, you can use a loop instead:
__fastcall TMyForm::TMyForm(TComponent *Owner)
: TForm(Owner)
{
int idx = 0;
for(int i = 0; (i < ComponentCount /* or: SomeParent->ControlCount */) && (idx < 64); ++i)
{
TImage *img = dynamic_cast<TImage*>(Components[i] /* or: SomeParent->Controls[i] */)
if (img)
Images[idx++] = img;
}
}
Alternatively, using the Form's FindComponent()
method:
__fastcall TMyForm::TMyForm(TComponent *Owner)
: TForm(Owner)
{
int idx = 0;
for(int i = 1; i <= 64; ++i)
{
TImage *img = dynamic_cast<TImage*>(FindComponent(_D("Image")+String(i)));
if (img)
Images[idx++] = img;
}
}