Passing data between forms in borland C ++ builder

I developed two forms in the C ++ builder:

  • Tfrmmain
  • TfrmChooseName

In the TfrmMain class, I have a button called btnNext. when you click btnNext, the code below runs and creates a new name TfrmChooseName.

frmChooseName = new TfrmChooseName(this); this->Hide(); frmChooseName->ShowModal(); this->Show(); delete frmChooseName; frmChooseName = NULL; 

also in TfrmMain I have a TEdit control named txtInput.
In costructor TfrmChooseName I want to get the text txtInput and set it as the title of the form, but there was an error accessing speed!
I also made both classes friends!

+4
source share
2 answers

The best way to handle this is to pass the desired Caption value to the constructor itself, rather than encode it to look up the value, for example:

 __fastcall TfrmChooseName(TComponent *Owner, const String &ACaption) : TForm(Owner) { Caption = ACaption; } 

.

 frmChooseName = new TfrmChooseName(this, txtInput->Text); 

Alternatively, you can set Caption after exiting the constructor, for example:

 frmChooseName = new TfrmChooseName(this); frmChooseName->Caption = txtInput->Text; 
+2
source

I think it is impossible to determine the exact problem without seeing more code. Creating class friends does not have to be necessary, because components added using the form designer have public access.

Have you TfrmChooseName from auto-update forms? If not, and if frmChooseName is a global variable that points to an automatically generated form, this can cause an access violation.

RADStudio documentation article Creating forms dynamically says:

Note. If you create a form using your constructor, make sure that the form is not in the "Automatically create forms" list on the "Project"> "Options"> "Forms" page. In particular, if you create a new form without deleting the same form from the list, Delphi creates the form at startup, and this event handler creates a new instance of the form, rewriting the link to the automatically created instance. An automatically created instance still exists, but the application can no longer retrieve it. After the event handler completes, the global variable no longer points to a valid form. Any attempt to use a global variable is likely to cause the application to crash.

You can also take a look at Creating an instance of a form using a local variable .

+2
source

All Articles