Skip to main content

Get and set C# application settings in runtime

Working with C# application or others .NET application, we usually use hard-code to manage the application settings, eg: control position, control label, control text, etc. However, with some settings, eg: database connections string, file directory, we should use app.config to store them. This  will help the settings easy to be  read and written dynamically.


Create an application setting for app.config:

  • Open your project in Microsoft Visual Studio. On Solution Explorer, right-click your project and choose Properties

  • In open windows, browse to Settings tab. Create a new setting key like setting1 and save it.

  • Now open app.config file. You will see the key.

Using the setting key by Properties.Settings.Default instance:
//get the setting value
txtCurrent.Text = Properties.Settings.Default.setting1;

//set the setting value
Properties.Settings.Default.setting1 = txtNew.Text;
Properties.Settings.Default.Save();

Example (download source code):

  • Design a windows form to read and write settings. Example as below picture.

  • Make some event to read and write settings:

private void Form1_Load(object sender, EventArgs e)
{
//get the setting value
txtCurrent.Text = Properties.Settings.Default.setting1;
}

private void btnSave_Click(object sender, EventArgs e)
{
if (txtNew.Text != string.Empty)
{
//set the setting value
Properties.Settings.Default.setting1 = txtNew.Text;
txtCurrent.Text = Properties.Settings.Default.setting1;
Properties.Settings.Default.Save();
}

Wish succeed! Video version here:

Comments

Popular posts from this blog

Integrate blogspot blogger blog with Dot TK free domain

Blogspot or Blogger is a blog service from Google. This service provides us many functions to make a small website as creating a blog, posting, commenting, . . . But there is a thing which might cause you dissatisfy. That's the blog address is too long, like http://www.your-tips-tricks.blogspot.com . If you own a short Dot TK domain , then your problems will be solved.