2013-09-24 91 views
2

我有以下代碼:My.Settings不保存變量

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 
    Else 
     MsgBox("Else executed") ' debug 
     strInitialDirectory = strDefaultFileDirectory 
     strInitialFile = strDefaultFileName 
     strInitialDirectory = My.Settings.strInitialDirectory 
     strInitialFile = My.Settings.strInitialFile 
    End If 
End Sub 
End Class 

基本上,形式加載時我想它檢查是否有在My.Settings任何東西,如果沒有,設置的值到默認值,但是當再次打開程序時,它不執行else語句,讓我相信我做錯了什麼,並且設置沒有保存。對此有何意見?謝謝。

+5

在加載事件的末尾添加My.Settings.Save – dbasnett

+0

@dbasnett DERP,謝謝。 – SCGB

回答

2

你必須調用My.Settings

My.Settings.Save() 

保存功能,您應在更新設置函數的末尾添加此。這將保存下一個會話的所有設置。

這裏我們的UpdateSettings函數的例子:

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 

    My.Settings.Save() 

    Console.WriteLine("Settings Saved") 
End Sub 
+1

它只適用於用戶設置。 – jcwrequests

1

嘗試使用的String.IsNullOrWhiteSpace()代替= Nothing

你的子改成這樣:

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