unlimit.in

A tutorial on using settings in C#

Written: 03 August 2013

Domain Registrations starting at $9.98*      

Sometimes when building windows applications, we need to save certain values so that we can reuse them when the application is started once again. Typically, these values are related to the properties of the application or a single form in the application. For example, we want to remember what was the width of the form so that when the application starts again we can set the form's width.

Settings will allow you to create and persist values between application sessions. How do we use settings?  Its very simple. Here are the steps -

1. Right click on the project in the Visual Studio, then Add -> New Item.


Right click to add

2. From the "Add New Item", select "Settings File" and give it a name. In the screenshot, the default name has been kept.

Right click to add

Next double click on the settings file in the solution explorer to open the design view of the file. It will look like this:

Main window of the tool

You will see four columns:

Just click and enter the settings as you need.

And here is the code to use these settings:

To retrieve settings:

    string color_to_use = Settings1.Default.Color;
   int width = Settings1.Default.Width;
   string email = Settings1.Default.Email;
          
To save settings:
    Settings1.Default.Width = 30;
          
If you try to save a setting with application scope, you will get the following error, which is expected as application scope variables are read-only.
    Property or indexer 'WindowsFormsApplication1.Settings1.Email' cannot be assigned to -- it is read only

          

Domain Registrations starting at $9.98*
blog comments powered by Disqus