Artisan
Artisan

Reputation: 4112

How to create a dialog at runtime and get a return value?

I want to create a dialog from current form class, and expect to get back a value from the dialog.

This is sample coding.

with TFormClass(FindClass('Tf_dialog_partner')).Create(Application) do
  try
    ShowModal;
    Value := DialogPublicVar;
  except
    Free; 
  end;

DialogPublicVar is a public variable of Tf_dialog_partner (TForm's descendant) class, for right now in my coding this current class doesn't use the Tf_dialog_partner's unit in the USES clause, I just use FindClass function, i can create a new form just fine.

This coding is error because this current class is not aware of Tf_dialog_partner's attributes, so it doesn't recognize DialogPublicVar.

Please help, how to make this current class to aware of DialogPublicVar.

Thanks everyone.

Upvotes: 0

Views: 1074

Answers (2)

sarutobi
sarutobi

Reputation: 11

Try this (for integer) or change on your type.

var a: Integer;  
...  
a := MyFormDialog.ShowDialog(...);  
if (a = 5)  
  DoWork()  
else  
  DoNotWork();  
...


function TMyFormDialog.ShowDialog(...): Integer;  
begin  
  ...  
  ShowModal;  
  ...  
  if(A)  
    result := 5;  
  else  
    result := 2;  
end;

Upvotes: 1

Remy Lebeau
Remy Lebeau

Reputation: 598329

If the value being returned is an integer, a simple option would be to have ShowModal() itself return the value. When the dialog is ready to close, it can set its ModalResult property to the desired value, and ShowModal() will return that value.

Otherwise, you can change the variable into a published property of the class, and then use RTTI to access it via the functions available in the TypInfo.pas unit.

Another option is to define an interface in a shared unit that the form class then implements, where the interface declares a method that the form overrides to retrieve the value. The rest of your code can then query the dialog for that interface via the Supports() function and call the exposed method.

Upvotes: 2

Related Questions