Storing and Retrieving Application User Settings

G_Waddell 6 Tallied Votes 2K Views Share

Hi,

Ever had an application that you want to store user specific settings on? e.g. login name or Form background colours, User specifc DSN connections etc. So the next time they run the app the information is there for them?

This can be achieved in VB.net with just a few easy steps.

  1. Set up your user level application setting.
  2. Write values to it
  3. Read those values back

1. Setting Up User Scoped Application
In the Solution Explorer Window, select your project and right click. Select the Properties option in the sub menu.
In the Properties Screen there should be a Settings tab, open it.
You should now see a grid with the following columns:
Name The Name you wish to give the settting
Type The Type of settng value e.g. String, Integer etc.
Scope User or Application, Pick USER as this is user specific and can be modified programatically while the application is running.
Value A default value for the setting

Application Scope is a system wide fixed value that writes to app.config which can be changed programmatically but this change can not be accessed until the project is reloaded. User Scope writes to a file in C:\Documents and Settings and can be accessed at any time by the program for the specific user.

2. Write Values to your Setting
As can be seen in the Example Sub StoreSettings once you have carried out step one above, you can read and write to these settings through the Settings Class.

To write to the setting simply use

My.Settings.[I]SettingName[/I] = [I]New Value[/I]

Important in order to store / keep these changes after the application closes you must save the update with

My.Settings.Save

Also note these settings are saved to a file text and are therefore accessible locally I DO NOT recommend you store passwords in them...


3. Reading Those Values back
As you can see from my example sub GetSettings, all you do is have the setting on the Right of the = e.g.

MyVar = My.Settings.MySettingName

NOTE if for what ever reason, you wish to reset a setting to the default, then the original settings can be restored from the App.config file by calling

My.Settings.Reload

I hope this helps someone out there....

Oxiegen commented: This is excellent +5
savedlema commented: Thanks for this. I'd like to know how I can modify the application scope settings. I will start a discussion on vb.net here. +2
sub StoreSetting(byRef UserName as String, byRef bgColor as String)

 With My.Settings
      .UserName = UserName
      .FormColor = bgColor
      .Save()
 End With
end sub


Sub GetSettings()
 Dim UserName As String
  UserName = My.Settings.UserName
  Me.BackColor = MySettings.bgColor
End Sub