Proper way to close a form with databinding

Proper way to close a form with databinding

Old forum URL: forums.lhotka.net/forums/t/3297.aspx


JohnB posted on Monday, July 30, 2007

I was checking out the code in the latest PT (3.0) and noticed that for the Close button on the ProjectEdit form the code calls the Cancel_Button_Click sub. Perhaps I'm missing something but why would you want to Rebind, Restore and Refresh when you are closing the form? Wouldn't it make sense to just to disable the events, unbind and close? Is there recommended way of unbinding?


    Private Sub Cancel_Button_Click(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles Cancel_Button.Click

    ' disable events
    Me.ProjectBindingSource.RaiseListChangedEvents = False
    Me.ResourcesBindingSource.RaiseListChangedEvents = False

    ' unbind the UI
    UnbindBindingSource(Me.ResourcesBindingSource, True, False)
        UnbindBindingSource(Me.ProjectBindingSource, True, True)

    ' rebind the UI
    Me.ResourcesBindingSource.DataSource = Me.ProjectBindingSource
    Me.ProjectBindingSource.DataSource = mProject

    ' restore events
    Me.ProjectBindingSource.RaiseListChangedEvents = True
    Me.ResourcesBindingSource.RaiseListChangedEvents = True

    ' refresh the UI
    Me.ProjectBindingSource.ResetBindings(False)
    Me.ResourcesBindingSource.ResetBindings(False)

  End Sub

  Private Sub CloseButton_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles CloseButton.Click

    Cancel_Button_Click(sender, e)
    Me.Close()

  End Sub


I also found this article which list the steps for "Save/Cancel in Windows Forms data binding".
http://www.lhotka.net/article.aspx?id=91e15def-fa1c-4236-86b5-b204bfc4a0aa

RockfordLhotka replied on Tuesday, July 31, 2007

It depends on whether there may be other references to the object in the application.

If your form is the only reference to the object, then you really don't need to do anything at all - just close the form and let the garbage collector do its job.

But if your object is referenced from elsewhere in the app, you need to cancel changes on the object. The key with doing this is to leave the object unbound, because as soon as you rebind the object, data binding will call BeginEdit() on your object(s).

In PTWin there are no other references, so you are correct that the call to the cancel click handler is technically unnecessary.

Copyright (c) Marimer LLC