Search code examples
delphidelphi-2010vcl

Reset a single form to its initial state


I have multiple forms in one project: frmBooking, frmWelcome, frmAdmin. I want to reset frmBooking (i.e., reset it to its initial state, as if it's just created with all the components) by clicking a button. I tried doing the following:

frmBooking.Destroy;
Application.CreateForm(TForm, frmBooking);
frmBooking.Show;

The result, however, is that it just creates a blank form, not resetting the form to its initial state.

What can I do to reset the form?


Solution

  • Based on your initial approach I put together some code.

    var
      theOwner: TComponent;
    begin
      { make sure that we don't kill ourselves. 
        can be omitted if we are sure it cannot happen. }
      theOwner := Owner;
      while theOwner <> nil do begin
        if theOwner = frmBooking then
          raise Exception.Create('cannot recreate owner form');
        theOwner := theOwner.Owner;
      end;
      
      { find out who must be the owner of the newly created instance }
      theOwner := frmBooking.Owner;
      frmBooking.Free;
      frmBooking := TfrmBooking.Create(theOwner);
      frmBooking.Show;
    end;