1

Let's suppose I have 2 forms: FormA and FormB. On FormA button click the instance of FormB is created and shown.

How to Dispose() FormB instance correctly after it has been closed?

To be more precise, let's suppose this is the code that creates a form:

    public void Settings(object sender, EventArgs e)
    {
        if (_settings == null)
            _settings = new Settings(_repositoryCollection, _config, this);

        _settings.Show();
        _settings.Focus();
    }
zerkms
  • 249,484
  • 69
  • 436
  • 539

1 Answers1

3

If you want a modal dialog, use

using (var settings = new Settings(_repositoryCollection, _config, this))
{
   settings.ShowDialog ();
}

Otherwise, for a normal form shown at the same time as FormA... you may not even have to. See this post.:

_settings = new Settings(_repositoryCollection, _config, this);
_settings.Closed += delegate {_settings.Dispose ();};
Community
  • 1
  • 1
agent-j
  • 27,335
  • 5
  • 52
  • 79
  • So just add it to `Closed` event? Is it ok to dispose an object from an event triggered by itself? – zerkms Jul 12 '11 at 03:44
  • "During that process, if the form was not shown modally, Dispose is called on the form." --- but the more I call that method - the more memory is consumed by application :-S – zerkms Jul 12 '11 at 03:47
  • If you want to be doubly sure that it's disposed, then yes. But `When a form is closed, all resources created within the object are closed and the form is disposed.` That applies to windows that are shown with `.Show`. – agent-j Jul 12 '11 at 03:47
  • Or even more strange - the memory consumption grows for the 7-9 window creatings after which it just stops growing more and stays the same value regardless new calls :-S So - seems like "everything is fine". Thanks. **UPD**: argh, nope - it grows the more I open that window :-S – zerkms Jul 12 '11 at 03:50