Thursday, June 30, 2011

C# Application Settings

Application Settings are a pretty cool feature and very simple to use with Visual Studio 2010, so first of all simply, what are they?

Application Settings allow you to abstract the details of storing data between program sessions.  Basically what this means is, you can add program settings and save their values so that the next time the program is run the setting will be remembered.  A similar feature is adding and using resources, but we'll be modifying our Application Settings ;)

Step 1.
Create a new Windows Forms Application.


Step 2.
Open the Settings file in the solution explorer pane.

Step 3.
Add a boolean setting, we will be using it in the next step.  At this step I should probably point out that we will want to be working with a "User" scope setting, as it we can modify it's value.  Application scope settings are more appropriate for program strings, like error messages or text blocks and other static items.  If you prefer the long version, please see the MSDN link at the bottom of this post.

Step 4.
Now then, the real magic.  Add a CheckBox control to the form, and view it's properties.  Go ahead and link the Toggle setting to "checked" as shown in the picture.


Step 5.
You may have already noticed if you have built and ran your application that your settings are not yet preserved, but why!?  Truth be told you must tell the settings when to save their state.

Fortunately, this is a very easy thing to do, so stick with me and I'll get to it.
Select the main form window, and add an event handler (by double-clicking)
for the FormClosing event, this is to save our program settings before the
application exits.


Step 6.
Now the fun part, the one that teaches you how to use the settings in your code!
In the event handler function body, add the following code:

Properties.Settings.Default.Save();

You may also notice a member of concern is: Properties.Settings.Default.Toggle

Alright, that's all folks.

5 comments:

  1. Very useful tips. I'm always trying to figure out this stuff.

    ReplyDelete
  2. Thanks for interpreting this stuff for me!

    ReplyDelete
  3. thanks for the tips i had to read this twice just to soak up the amount of information in this post but thanks a bunch

    ReplyDelete
  4. Wooah lots of good information, took me a while to understand it lol.

    ReplyDelete