Ziff-Davis Enterprise 
DevSource: Microsoft Developer Resource
Add OnsArchitectureLanguagesTechniquesUsing VSForums
 
Home arrow Languages arrow VB.NET: Using My.Settings for Application Settings
VB.NET: Using My.Settings for Application Settings
By Peter Aitken

Rate This Article:
Add This Article To:
A perennial problem that faces most developers is where to store program settings. Various approaches have been used for this. However, in VB.NET, storing application settings is easy thanks to the My.Settings object. Peter Aitken shows you how.

A perennial problem that faces most developers is where to store program settings. Various approaches have been used for this, including the system registry, the application configuration file, and a custom serializable object. I explored some of these in my earlier article Saving user Settings. Just recently I came across another method for saving user and application settings, one that is so convenient and easy that I felt like banging my head on the wall for not knowing about it earlier. However, better late than never, and I am going to tell you about my find in this article. I am talking about My.Settings, of course.

First, be aware that My.Settings--in fact the entire family of My objects--is Visual Basic only. Too bad for the C# programmers, but it does give us VB programmer something else to crow about! Settings are in fact available to C# developers, just not in such an easy-to-use form, so don't crow too loudly.

ADVERTISEMENT

My.Settings distinguishes between user settings, which may change each time the program is run, and application settings, which do not. You will employ user settings for things that the user may change and you want restored the next time the program runs, such as default fonts and colors, window positions, and toolbar options. In contrast, application settings are meant for settings that the developer may want to change but the user should not be able to, such as database connection strings. Yes, you could always hard-code such information in your source code, but using My.Settings is so much easier.

Settings are associated with a project. To define or modify settings, open the Project menu in Visual Studio and select <Project Name> Properties (where <Project Name> is the name of your project). In the Properties window, select Settings from the list on the left. The window will look like the first figure below. Here, no settings have yet been defined. To define a setting:

1. Click where it says Setting.

2. Type in the name of the setting. Names must be unique and cannot contain spaces.

3. Pull down the Type list and select the data type of the setting. The default is String, but you can choose from any of VB.Net's data types.

4. Under Scope, select whether the setting should have User or Application scope (as explained above).

5. If you want the setting to have a default value, enter or select it in the Value field.

In the figure to the left, the Settings window lets you define application and user settings.

The figure below shows the Settings window after a few settings have been defined. If you should want to remove a setting, right-click it and select Remove Setting from the popup menu. Editing a setting is done just as you would expect.

Near the top of the Settings window are two commands which you use as follows:

Synchronize: It's a badly chosen name, but what it does is return all settings to the values that were defined in the Settings window. If you have been running the application in the development environment and making changes to user settings, this lets you return to the default state, a good idea before distributing the program.

View Code: Opens a code editing window with the code for the MySettings class (which is in the Settings.vb file). You can define settings-related events here, as will be covered in more detail soon.

Using Your Settings

In your program, settings are automatically available to your code using the syntax My.Settings.SettingName. For example:

Private Sub Form1_FormClosing(ByVal sender As Object, _
ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If My.Settings.PromptForExit Then
    If MsgBox("Exit program?", MsgBoxStyle.YesNo) = MsgBoxResult.No Then
        e.Cancel = True
    End If
End If
End Sub

You can set and retrieve user settings and retrieve application settings. Changes you make to user settings are saved automatically when the program shuts down. If you want to save them immediately, call My.Settings.Save to do so. If you want to restore all settings to the values they had when the program started, call My.Settings.Reload.

Creating a Settings Grid

You may want to design your own settings dialog box to allow your users to view and edit settings. However, it is ridiculously easy to create a property grid that is bound to My.Settings. First, add a PropertyGrid control to a form. Next, add the following code to the Form_Load event procedure:

PropertyGrid1.SelectedObject = My.Settings

The grid will display all of your settings, as shown in the figure to the right. By default, both user settings and application settings are shown, although the latter are not editable. If you want the grid to display only the user settings, place this code right after the code that binds the property grid to My.Settings:

Dim userAttr As New System.Configuration.UserScopedSettingAttribute
Dim attrs As New System.ComponentModel.AttributeCollection(userAttr)
PropertyGrid1.BrowsableAttributes = attrs

Settings-Related Events

Four settings-related events are available and are used primarily to validate setting values:

  • SettingChanging: This event is raised before a setting's value is changed.
  • PropertyChanged: This event is raised after a setting's value is changed.
  • SettingsLoaded: This event is raised after the setting values are loaded.
  • SettingsSaving: This event is raised before the setting values are saved.

You would probably never use all of these events in the same application. The one you use will depend on the approach you want to take to validation. SettingChanging occurs before the setting is actually changed and can be used to provide immediate feedback to the user. Note that there will be only one SettingChanging event procedure no matter how many settings you have--you get the name of the setting that is being changed from the procedure arguments. For example, suppose your application has a NextBackup setting that specifies the date and time the next automatic backup will occur. Obviously this date/time must be in the future. This validation code, in the SettingChanging event procedure, does just this. If the date/time is not in the future, the change is cancelled and the old setting value retained.

Private Sub MySettings_SettingChanging(ByVal sender As Object, _
ByVal e As System.Configuration.SettingChangingEventArgs) Handles Me.SettingChanging
    If (e.SettingName.Equals("NextBackup")) Then
        Dim NewDate as Date = CType(e.NewValue, Date)
        If (NewDate > Date.Now) Then
           e.Cancel = True
           ' Display message to the user.
        End If
    End If
End Sub

PropertyChanged fires after the setting has been changed and is rarely used except in cases where the validation procedure is time-consuming (for example, when validation criteria must be obtained from a remote location). SettingsSaving can be used to validate multiple settings when they are saved (When My.Settings.Save is called or when the application closes). SettingsLoaded can be used to validate the saved settings when they are first loaded and before they are used in the application.

Summing Up

Programming tools are supposed to make the developer's life easier. Customers are very demanding, and the last thing you want to do is spend a lot of time creating an app's basic plumbing. Saving user and application settings is often an important part of this plumbing, and with My.Settings the task is easier than ever.




Discuss VB.NET: Using My.Settings for Application Settings
 
Hi Peter is it possibile to show in the setting description (you can set this in...
>>> Post your comment now!
 

 
 
>>> More Languages Articles          >>> More By Peter Aitken
 



DevSource video
Devsource Video Series
Manipulating Society through Technology
Jeremy Bailenson, Director of the Virtual Human Interaction Lab at Stanford University, talks about virtual reality, avatars, Moore's law, how real world behaviors influence online reality, and societal manipulation through technology!
>> Play video
>> Read article
>> See all videos
DevLife Blog
Julia shows you some wicked cool use of LINQ!
MSDev Blog
Is the latest Delphi product, RAD Studio 2007, really necessary?
Make it Work
.NET makes runtime type checking a breeze. See what Peter has to say about it in this week's tips!
News
Microsoft Counts on App Support for Vista
Microsoft has taken pains to demonstrate that Windows Vista will have ample application support.
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.