Sam Cousins Sam Cousins - 1 year ago 123 Question

My.Settings not saving variables

I have the following code:

Imports System.IO

Public Class Form2

Dim strInitialDirectory As String
Dim strInitialFile As String
Const strDefaultFileDirectory As String = "C:\Users\Sam\Desktop\Visual Basic\Test"
Const strDefaultFileName As String = "\test.txt"
Dim strFileJPath1 As String = strInitialDirectory + strInitialFile
Dim strFileJPath2 As String = strDefaultFileDirectory + strDefaultFileName

Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If My.Settings.strInitialDirectory = Nothing Or My.Settings.strInitialFile = Nothing Then
My.Settings.strInitialDirectory = strDefaultFileDirectory
My.Settings.strInitialFile = strDefaultFileName
MsgBox("Else executed") ' debug
strInitialDirectory = strDefaultFileDirectory
strInitialFile = strDefaultFileName
strInitialDirectory = My.Settings.strInitialDirectory
strInitialFile = My.Settings.strInitialFile
End If
End Sub
End Class

Basically, when the form loads I'd like it to check if there is anything in My.Settings and if not, set the values to the defaults, however upon opening the program again, it does not execute the else statement, leaving me to believe I'm doing something wrong and the settings aren't saving. Any input into this? Thanks.

Answer Source

You have to call the save function in My.Settings


You should add this at the end of an update settings function. This will save all the settings for the next session.

Here us an example of an UpdateSettings function:

Private Sub UpdateSettings()

    Console.WriteLine("Saving Settings")

    My.Settings.WO_imprevu = CheckBoxImprevu.Checked
    My.Settings.WO_prevu = CheckBoxPrevu.Checked
    My.Settings.Date_type = ComboBoxDateType.SelectedIndex
    My.Settings.Date_debut = DateTimePickerDebut.Value


    Console.WriteLine("Settings Saved")
End Sub
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download