Bobski Bobski - 1 month ago 6
Vb.net Question

Vb.Net check to see if selection/text was changed in form

I have a form with about 20 controls (comboboxes, textboxes, etc) that I pre-load with data. This is being displayed to the user and gives them the capability to change any of the fields. My question/quandary is that I do not know the best way of recognizing that changes have taken place. After some research, it shows that textbox.textChanged and setting a flag IsDirty = True or something along those lines.

I don't think this will be 100% bulletproof since user might change the value and then go back and change it to how it was when it initially loaded. I've been thinking about saving the current data as to .tag and then comparing it with the .text that was entered when they click "Cancel" to simply ask them if they'd like to save the changes, code looks like this...

PrivateSub Form1_Load(ByVal sender as Object, byVal e as System.EventArgs)Handles MyBase.Load
For Each ctr as Control in me.Controls
if typeof ctr is TextBox then
ctr.tag=ctr.text
end if
Next
End Sub


And then when user clicks cancel, do something like...

Private Sub CmdCancel_Click (ByVal sender as Object, ByVal e As System.EventArgs) Handles CmdCancel.Click
For each ctr As Control in Me.Controls
If Typeof ctr is Textbox then
if ctr.tag.tostring <> ctr.text then
MsgBox ("Do you want to save the items", YesNo)
end if
End if
Next
End sub


Is this an effective way to do this? Can it be relied on? If anyone has any better idea, I'd love to hear it.

Answer

Have a look at this:

For Each txtBox In Me.Controls.OfType(Of TextBox)()
    If txtBox.Modified Then
        'Show message
    End If
Next

EDIT

Have a look at this. This may be of interest to you if you wanted an alternative way to the .Tag property:

'Declare a dictionary to store your original values
Private _textboxDictionary As New Dictionary(Of TextBox, String)

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    'You would place this bit of code after you had set the values of the textboxes
    For Each txtBox In Me.Controls.OfType(Of TextBox)()
        _textboxDictionary.Add(txtBox, txtBox.Text)
    Next

End Sub

Then use this to find out the original value and compare to the new value:

For Each txtBox In Me.Controls.OfType(Of TextBox)()
    If txtBox.Modified Then
         Dim oldValue = (From kp As KeyValuePair(Of TextBox, String) In _textboxDictionary
                         Where kp.Key Is txtBox
                         Select kp.Value).First()
         If oldValue.ToString() <> txtBox.Text Then
             'Show message
         End If

    End If
Next