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

Turn off AutoPlay on Windows

On Windows, when you insert an USB or a CD/DVD into your computer, they are usually opened automatically. So the computer maybe infected autorun virus. To avoid that, you should turn off AutoPlay function.

Create Wordpress page template

When creating a new page in Wordpress, we usually have a choice for the page template. It's call Default template . However, we sometimes need to make a new page with a new appearance. Then another page template is needed. Instead of downloading a shared page template from internet, we can create a new page template by below instructions.