Search code examples
vb.netmy.settings

Reset My.Settings to values last saved


I'm currently using a "Settings" form to set various settings for my application. What I'm trying to do is to revert settings back to before any changes the user has made before opening and changing a field. I have a text box with a data binding to a setting and when I make a change and click okay it gets saved the next time I open it. When I hit cancel it also gets saved. Not quite sure if I'm approaching this correctly.

Public Class frmSettings
    Private _mysettings As Configuration.SettingsBase

    Private Sub frmSettings_Load(...) Handles Me.Load
        _mysettings = My.Settings
    End Sub

    Private Sub btnCancel_Click(...) Handles btnCancel.Click
        For Each p As Configuration.SettingsPropertyValue In _mysettings.PropertyValues
            My.Settings(p.Name) = p.PropertyValue
        Next
        Me.Close()
    End Sub

    Private Sub btnOkay_Click(...) Handles btnOkay.Click
        My.Settings.Save()
        Me.Close()
    End Sub
End Class

Solution

  • Rather than using databound control you can simply load the value of the setting when the settings form loads. It is simple doing it that way, and it works. Otherwise you would have to make a clone of My.Settings: doing _mysettings = My.Settings is only creating a pointer to My.Settings, not a copy of it.

    For example, I have a Form named ChangeConnectionString which has OK/Cancel buttons and a TextBox control named connString:

    Public Class ChangeConnectionString
    
        Private Sub bnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bnOK.Click
            My.Settings.connectionString = connString.Text
            My.Settings.Save()
            Me.Close()
        End Sub
    
        Private Sub bnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bnCancel.Click
            Me.Close()
        End Sub
    
        Private Sub ChangeConnectionString_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            connString.Text = My.Settings.connectionString
        End Sub
    
    End Class