Question

I designed two forms in c++ builder:

  • TfrmMain
  • TfrmChooseName

In TfrmMain class I have button named btnNext. when btnNext is clicked, code below runs and creates new TfrmChooseName.

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

also in TfrmMain I have TEdit control named txtInput.
In costructor of TfrmChooseName I want to get text of txtInput and set it as a caption of form but access volation error occured!
I also made both classes friend!

Was it helpful?

Solution

The best way to handle this is to pass the desired Caption value to the constructor itself, rather than code it to hunt for the value, eg:

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

.

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

Alternatively, you can set the Caption after the constructor exits, eg:

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

OTHER TIPS

I think it's not possible to detect the exact problem without seeing more of the code. Making the classes friends shouldn't be necessary, since components added using the form designer have public access anyway.

Have you removed TfrmChooseName from Auto-Create forms? If not, and if frmChooseName is the global variable pointing to the auto-created form, that might cause the Access Violation.

The RADStudio Documentation article Creating Forms Dynamically says:

Note: If you create a form using its constructor, be sure to check that the form is not in the Auto-create forms list on the Project > Options > Forms page. Specifically, if you create the new form without deleting the form of the same name from the list, Delphi creates the form at startup and this event-handler creates a new instance of the form, overwriting the reference to the auto-created instance. The auto-created instance still exists, but the application can no longer access it. After the event-handler terminates, the global variable no longer points to a valid form. Any attempt to use the global variable will likely crash the application.

You may also want to take a look at Creating a Form Instance Using a Local Variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top