I created a program in C++Builder 6 and I have a problem now.
I have 6 files: Unit1.cpp, Unit1.h, Unit2.cpp, Unit2.h, Unit3.cpp, Unit3.h.
Unit1.cpp is file for main form.
Problem : I want to create in Function void __fastcall TForm3::Button1Click(TObject *Sender) a TStringGrid which will be visible in Unit1.cpp and Unit2.cpp. Next click should create new TStringGrid with new name(previous exist)
I tried to fix my problem, I wrote some code, but it is not enough for me.
In Unit1.h I added:
void __fastcall MyFunction(TStringGrid *Grid1);
In Unit1.cpp I added:
void __fastcall TForm1::MyFunction(TStringGrid *Grid1)
{
Grid1 = new TStringGrid(Form2);
Grid1->Parent = Form2;
}
In Unit3.cpp I added:
#include "Unit1.h"
and the Button click function is:
void __fastcall TForm3::Button1Click(TObject *Sender)
{
Form1->MyFunction(Form1->Grid); //Grid was declarated previous in Unit1.h
}
Now when I used this method I dynamically create a TStringGrid, but only one. How do I create as many TStringGrids (with unique names) as the number of times the button is pressed? (Now i must declarate TStringGrid in Unit1.h).
First, note that your code is creating multiple
TStringGrids. It is just creating them all with the same dimensions in the same place on the form, so you only see the one on top.--
What you want to be able to do (
Form1->dynamically_created_TStringGrid) is not possible, but there are a couple of methods available to you to get similar behavior.The std::vector method
Unit1.h
Unit1.cpp
Using this method you could call
AddStringGrid()and store the return value. Then when you wanted to manipulate a givenTStringGridonForm1you would callGetStringGridByNameand pass in the name of theTStringGridyou want to manipulate. You could also implement something very similar with astd::map, even as apublicmember.The FindChildControl method
Unit1.h
Unit1.cpp
This version basically uses the
Parent -> Childrenrelationship to find the dynamically createdTStringGridinstead of storing it in astd::vector.My gut says that it is slower and less safe than thestd::vectormethod, but I don't have any proof. It also doesn't offer any simple, reliable way to get at theStringGrids if you "forget" the unique names you gave them, while thestd::vectorlets you access them by index, or via an iterator if you make one available. There isGetChildren, but it does not look very intuitive to use.--
At first I thought you would get a memory leak every time you call
TForm1::MyFunction, but if I'm understanding the Builder 6 documentation correctly, that is not the case:So even though you are assigning a
newed object to Grid1 every time you pass it in to that function, those objects are still owned byForm2and will be cleaned up whenForm2is destructed.All that said, you should be aware that, if you stick with the implementation you have posted in the OP, you won't be able to manipulate any of your string grids except for the last one unless you access them from
Form2->Array.