March 11, 2006

Winforms 2.0: Application Settings

OK, I'm defiantly getting behind the times. But in my defense, I don't get many chances to use WinForms these days -- I'm still waiting for my great excuse to use Click-Once.

What did I miss all this time: Application Settings. This is not entirely new, we have had app.Config for a long time now, and the Settings class/designer uses the app.Config.

Couple of differences though:
  1. It is type safe. You add a property thru the designer, then you can access that value thru its property. Nice. (I'll show more on this in a minute)
  2. You can change the values, and there is a Save method!
  3. There is a setting for User vs. Application settings
Other items worth knowing: it can save any data that serializes to XML, but has problems with null data.

To add a settings class to a C# project: Right click on the project (like you do to add a class or a form), select Add->New Item.... Then select Settings File from the bottom of the list, and give it a name -- I called mine Settings1.

That produced a file called Settings1.settings in the designer.

To access the properties stored in the settings class, I use Settings1.Default..

Also, you can access the code behind the designer for the settings object. Be warned, it is generated code, and it will get overwritten from time to time.

There are some differences between the VB version of this and the C#, but those are documented in the source. The main difference is that the settings class is included in the My object, and C# has to use the method shown above. This is complicated by the fact that most of the documentation seems to cater to the VB crowd.

One final note that has to be looked into. All of the settings in the Settings class are ultimatly stored in the app.config file. Application level settings are stored in the node, and user settings are stored in the node.

Now how does that work for multiple users?

2 comments:

Anonymous said...

Thanks for that info - it came in handy!

Sharma said...

that really helpfull . Can u post any article illustrating how to add and retrieve settings and how to get all the values listed in a listbox ..
I'll be relly thankfull to u if u do so BEcause i m just hanging in here just for this else my whole project is completed ..

Thanks In advance

Suraj Sharma
S3 Technology