0

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
  • Not for nothing, but based on your comment below, serializing your Settings class is a great way to simplify Save/Load. With the data in the class, save it all to a file in 3 or 4 lines, reload the data next time in just as few. no need to read values or post them back to MySettings – Ňɏssa Pøngjǣrdenlarp May 11 '14 at 00:25

1 Answers1

0

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
Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
  • Thanks for the answer Andrew. What I ended up doing overall was creating a couple of classes to hold the settings and just looping through it when the form loads to save the settings. Then if I cancel, I loop back through the saved settings and reset the My.Settings. The settings page I have has 30+ settings and I was trying to save some space. – weekendclimber May 10 '14 at 21:57