【问题标题】:Delphi - Form Properties empty on FormCreate when set from other FormDelphi - 从其他表单设置时,FormCreate 上的表单属性为空
【发布时间】:2023-04-03 14:54:01
【问题描述】:

这是一个有趣的案例。

拥有登录表单,其中设置了一些变量值,例如 company_id 和 SelectedlanguageCode,其想法是将这些值传递给 MainForm 属性以加快速度(选择的语言代码转到数据库进行查询),这些值将是在 FormCreate 事件中立即需要,但这里缺少值,但在 CreateForm 事件后调试,值只是显示。

这是项目源代码:

{$R *.res}

Var
  LoginOK: Boolean = False;
  sCompanyId: integer;
  sSelectedLanguageCode: string;
begin
  // The login form is created and show up
  // --------------------------------------

  fLogin := TfLogin.Create(nil);
  try
    // Show login form. When it closes, see if login worked.
    fLogin.ShowModal;
    LoginOK := fLogin.CanLogin;         
    sCompanyId := fLogin.pCompanyId;
    sSelectedLanguageCode := fLogin.gDefaultLanguageCode;
  finally
    fLogin.DisposeOf;
  end;

  if not LoginOK then
    Halt;    // Login failed - terminate application.

  Application.Initialize;

  Application.MainFormOnTaskbar := True;
  Application.CreateForm(TfMain, fMain);
  // Here the properties of Main are set with the values, 
  // when debugging the properties get the values, you can
  // see the actual values when hovering over the property
  fMain.gSelectedLanguage := sSelectedLanguageCode;
  fMain.gUserCompany := sCompanyId;
  Application.Run;
end.

但如前所述,在 Main 的 CreateForm 中,属性为空... 并且...在 CreateForm 事件之后,属性具有实际值。

我在 CreateForm 事件中需要这些值,因为某些方法将被调用并需要发送它们...

我很感激关于正在发生的事情的答案,以了解我做错了什么,或者如果有充分的理由这样做的话......如果你能给我另一种方法来解决这个要求,谢谢。

【问题讨论】:

  • 如果我对您的理解正确,您将面临先有鸡还是先有蛋的困境。您不能在创建表单之前设置属性,但在创建表单期间您已经需要这些值。因此,将这些变量作为全局变量(颤抖)放在主窗体单元中。然后您可以在创建表单之前设置它们,并且您的主表单可以在需要时读取它们。
  • Application.CreateForm 返回时,表单已经创建并且FormCreate 已经执行。显然,当您在 之后 FormCreate 已经运行后才设置它们时,它们无法在 FormCreate 中使用。
  • Tom,就是这样完成的,提供的代码是应用程序代码,它首先创建登录表单,然后在用户登录后创建主表单并分配登录名值,释放登录表单并显示 Main。我一直在 Main 属性中使用这些值来使用它们,效果很好,但是直到我在 CreateForm 事件中需要它们时,我才意识到特别是那里的值还不可用,就在那里。
  • 您可以尝试覆盖 fMain 的构造函数,以便您可以在构造函数中传递值。而不是 Application.CreateForm() 它将是这样的: fMain = TfMain.Create(Application, sSelectedLanguageCode, sCompanyID) 有关如何执行此操作的信息,您可以在此处找到stackoverflow.com/questions/26132808/…

标签: oop delphi


【解决方案1】:

好的,所以不要将初始化代码放在 formCreate 中,而是将其全部移动到主窗体上的方法中(例如 init())。 然后在 application.run 之前的行中,您可以拥有 主窗体.init; 或者 mainform.init(sSelectedLanguageCode, sCompanyId);

我总是将创建与初始化分开。如果显示表单并且未初始化,则可以引发错误。即在 onShow 中,如果没有公司 ID - 告诉用户出现错误并关闭应用程序....

【讨论】:

    猜你喜欢
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多