0
votes

I am looking for a way to save and load the values of all my controls present in my form. My form has around 100 controls spread over 7 tabs. The controls include (Multiline) TextBoxes (Strings), NumericUpDowns (Integers, Decimals) and Checkboxes (Booleans).

If the user clicks the save button a "Save File" dialog should appear allowing the user to specify the directory and the filename of the save file. All the values of the controls should then be written to that file.

If the user clicks the load button an "Open File" should appear where the user can pick a previously saved save file. All the controls should then adopt the values found in the save file.

I have implemented Application Settings in my form, and now when I click save, it saves the control values through My.Settings.Save(). If I click load it loads them.
However, my project requires that multiple save files can be made to reflect multiple configurations. As I understand Application Settings only allow for a single .config file in the Application Data folder.

So how can I code a save/load routine to save/load different configurations?

1

1 Answers

0
votes

The code found at this site provides another Provider to handle the Application Settings. It is possible to code the target destination of the .settings files.

I added a CopyFile routine to copy the generated .setting file to the same directory but with a different name, specified by the user. The code:

    If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
        Dim savefile As String
        savefile = SaveFileDialog1.FileName
        Try
            My.Computer.FileSystem.CopyFile(My.Application.Info.Title & ".settings", savefile, True)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    Else
        'Nothing
    End If

Now to load the user-saved settings again I've made Load routine which copies the chosen file to the root folder and overwrites "Form1.settings"

    If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
        Dim loadfile As String

        loadfile = OpenFileDialog1.FileName

        Try
            My.Computer.FileSystem.CopyFile(loadfile, My.Application.Info.Title &    ".settings", True)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        Application.Restart()
    Else
        'Nothing
    End If

The routine performs an Application.Restart() such that the Form1_load event is performed and the controls copy the values in the .settings file

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
     TextBox1.Text = My.Settings.Text1 
End Sub

Now when the user clicks save, the My.Settings.Save() is executed and the Form1.settings file is copied to a user specified .settings file.
When the user clicks load the user specified .settings file is overwriting Form1.settings and the application restarts, reading in the values from the Form1.settings file.