vb.netwinformsdirty-checkingdirty-tracking

Check if any control has changed and save data upon form closing


We are using vb.net / dev express tools. We have several controls textboxes, combos etc... instead of checking each value changed we want to go through all controls and check if anything has been edited, then save upon form closing. Below is some code i have tried to accomplish this. Problem is, although it technically works... it uses recursion AddDirtyEvent(c) , so when i go to close the form and click yes to save.. it calls that messagebox multiple times due to multiple controls... if i take that out , it won't work and detect the dirty change. I'm just wondering how can i get this to work the way i want or if there is an easier way...

 Dim is_Dirty As Boolean = False

  Private Sub AddDirtyEvent(ByVal ctrl As Control)

    For Each c As Control In ctrl.Controls
        If TypeOf c Is TextEdit Then
            Dim tb As TextEdit = CType(c, TextEdit)
            AddHandler tb.EditValueChanged, AddressOf SetIsDirty

        End If
        'If TypeOf c Is ComboBoxEdit Then
        '    Dim cb As ComboBoxEdit = CType(c, ComboBoxEdit)
        '    AddHandler cb.SelectedIndexChanged, AddressOf SetIsDirty

        'End If
        If c.Controls.Count > 0 Then
            AddDirtyEvent(c)
        End If

    Next

End Sub

Private Sub SetIsDirty(ByVal sender As System.Object, ByVal e As System.EventArgs)
    is_Dirty = True
End Sub

Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing

    If is_Dirty = True Then
        Dim dr As DialogResult = MessageBox.Show("Do you want save changes before leaving?", "Closing Well Info", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2)
        If dr = Windows.Forms.DialogResult.Yes Then
            SimpleButtonSave.PerformClick()
            Me.Close()
        End If
    End If
End Sub

Solution

  • The part of your code that handles the events and sets the dirty flag works OK.

    Your MessageBox appears multiple times because you are calling Me.Close within the FormClosing event handler. Calling Close triggers the FormClosing event again - recursively. Just remove the Me.Close; the form is already closing.