IsDirty Change Tracker for WinForms

Here is a ChangeTracker class I developed for use in WinForms scenarios – it is adapted from an article I found at The Code Project site.  In testing it, I also came across a problem and work-around for DataGridView controls – see the next blog post for details.

To use this class, download the class file and add it to your project.  In the form in which you want to track changes, add a form level variable:

Private changeTracker As TKS.ChangeTracker

In the form’s Load event, put the following code:

'set up change tracking
Me.changeTracker = New TKS.ChangeTracker(Me)

In the form’s FormClosing event, put the following code (you can see a clue as to the next blog entry in the first line):

'set focus on a textbox control, to make sure that datagrid CellChangeValue event fires if necessary

'check if form is dirty
If Me.changeTracker.IsDirty Then
Dim result = MessageBox.Show("Would you like to save changes before exiting?", "Save Changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
Select Case result
Case Windows.Forms.DialogResult.Yes
Case Windows.Forms.DialogResult.No
'no action needed, unless form is hidden instead of closed. Then, you might want to re-set the change tracker
Case Windows.Forms.DialogResult.Cancel
e.Cancel = True
End Select
End If

And here is the code for the class itself.  It is written to check TextBoxes, CheckBoxes, ComboBoxes, CheckedListBoxes and DataGridViews, but you can adapt it to check whatever you want. (You can also download the code.):

Namespace TKS
Public Class ChangeTracker

#Region "Data Members"
Private _frmTracked As Form
Private _ctlData As Generic.Dictionary(Of String, TKS.ChangeTracker.ControlInfo)
#End Region

#Region "Constructor"
Public Sub New(ByVal frm As Form)
'initialize data members
_frmTracked = frm
_ctlData = New Generic.Dictionary(Of String, TKS.ChangeTracker.ControlInfo)

'get initial control values, and hook up tracking events
Me.SetUpControlTracking(_frmTracked.Controls, isEventsAssigned:=False)
End Sub
#End Region

#Region "Properties"
Public ReadOnly Property IsDirty As Boolean
'loop through the change-tracker object for each control.  If any is dirty, exit loop and return true
For Each kvPair As KeyValuePair(Of String, ControlInfo) In _ctlData
If kvPair.Value.IsDirty Then Return True
'if we've gotten here, then nothing is dirty - return false
Return False
End Get
End Property
#End Region

#Region "Methods"
Public Sub SetAsClean()
'clear previous data
'get new control values - don't need to hook up events as they are already hooked up
Me.SetUpControlTracking(_frmTracked.Controls, isEventsAssigned:=True)
End Sub

Private Sub SetUpControlTracking(ByVal col As Control.ControlCollection, ByVal isEventsAssigned As Boolean)
'loop control collection, add control value to info collection, add event handler to designated controls if it hasn't been done already
For Each ctl As Control In col
If TypeOf ctl Is TextBox Then
Dim txtbox = CType(ctl, TextBox)
_ctlData.Add(txtbox.Name, New ControlInfo(txtbox.Text, False))
If Not isEventsAssigned Then AddHandler txtbox.TextChanged, AddressOf TextBox_TextChanged

ElseIf TypeOf ctl Is CheckBox Then
Dim chkbox = CType(ctl, CheckBox)
_ctlData.Add(chkbox.Name, New ControlInfo(chkbox.Checked.ToString, False))
If Not isEventsAssigned Then AddHandler chkbox.CheckedChanged, AddressOf CheckBox_CheckedChanged

ElseIf TypeOf ctl Is ComboBox Then
Dim cbobox = CType(ctl, ComboBox)
_ctlData.Add(cbobox.Name, New ControlInfo(cbobox.SelectedValue.ToString, False))
If Not isEventsAssigned Then AddHandler cbobox.SelectedIndexChanged, AddressOf ComboBox_SelectedIndexChanged

ElseIf TypeOf ctl Is CheckedListBox Then
Dim lstbox = CType(ctl, CheckedListBox)
_ctlData.Add(lstbox.Name, New ControlInfo(Me.GetAllChecked(lstbox), False))
If Not isEventsAssigned Then AddHandler lstbox.SelectedIndexChanged, AddressOf CheckedListBox_SelectedIndexChanged

ElseIf TypeOf ctl Is DataGridView Then
Dim dg = CType(ctl, DataGridView)
Dim key As String
'will need to loop datagrid and get each cell value.  Concatenate grid name, row index, cell index to create unique key for each cell.  Skip rows with no values.
For Each row As DataGridViewRow In dg.Rows
If Not row.IsNewRow Then
For Each cell As DataGridViewCell In row.Cells
key = dg.Name & row.Index.ToString & cell.ColumnIndex.ToString
_ctlData.Add(key, New ControlInfo(cell.Value.ToString, False))
End If
If Not isEventsAssigned Then AddHandler dg.CellValueChanged, AddressOf DataGridView_CellValueChanged
End If

'recursively get values from, add event handlers to, child controls
If ctl.HasChildren Then
SetUpControlTracking(ctl.Controls, isEventsAssigned)
End If
End Sub
#End Region

#Region "Event Handlers"
'Event handlers will:
'  - get control's change-tracker object from collection
'  - get control's new value and pass to 'CheckIfDirty' method of change-tracker object
'  - if new value is different from saved value, 'CheckIfDirty' will mark control as dirty
'  - if new value restores saved value, 'CheckIfDirty' will change control back to clean
Private Sub TextBox_TextChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim txtbox = CType(sender, TextBox)
If _ctlData.ContainsKey(txtbox.Name) Then
End If
End Sub

Private Sub CheckBox_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim chkbox = CType(sender, CheckBox)
If _ctlData.ContainsKey(chkbox.Name) Then
End If
End Sub

Private Sub ComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim cbobox = CType(sender, ComboBox)
If _ctlData.ContainsKey(cbobox.Name) Then
End If
End Sub

Private Sub CheckedListBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim lstbox = CType(sender, CheckedListBox)

If _ctlData.ContainsKey(lstbox.Name) Then
End If
End Sub

Private Sub DataGridView_CellValueChanged(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
Dim dg = CType(sender, DataGridView)
Dim row = dg.Rows(e.RowIndex)
Dim cell = row.Cells(e.ColumnIndex)
Dim key As String = dg.Name & e.RowIndex.ToString & e.ColumnIndex.ToString

'if key exists, check against initial value
If _ctlData.ContainsKey(key) Then
'if key doesn't exist, this is a new row - add cell, and set as dirty  (set value to something unlikely so control will always evaluate as dirty)
_ctlData.Add(key, New ControlInfo("-TKS", True))
End If
End Sub
#End Region

#Region "Get All Selected Values in List"
Private Function GetAllChecked(ByVal lstBox As CheckedListBox) As String
'loop through 'CheckedIndices' collection and concatenate
Dim sb As New System.Text.StringBuilder
For Each i As Integer In lstBox.CheckedIndices
Return sb.ToString
End Function
#End Region

#Region "ControlInfo Class"
'change-tracker object - stores control's initial value and evaluates new values
Private Class ControlInfo
Sub New(ByVal v As String, ByVal dirty As Boolean)
Value = v
IsDirty = dirty
End Sub

Public Property Value As String
Public Property IsDirty As Boolean

Public Sub CheckIfDirty(ByVal newValue As String)
If Me.Value.Equals(newValue) Then
Me.IsDirty = False
Me.IsDirty = True
End If
End Sub
End Class
#End Region

End Class
End Namespace

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s