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.

Install and play Pokemon Go on unsupported device

Pokemon Go is great mobile game for smart devices (Android, iOS...). Many people can install and play it normally. However, some device has not been supported yet (Intel inside smartphone: Asus Zenfone, Dell Veune, ...; Windows Phone devices...). Here we show you how to play it in all your devices. For Android devices: Enable “Unknown sources” in the settings. Download Pokemon Go app setup:  Link 1  / Link 2   Open the downloaded file to install app. Enable all the settings when promted. Now you can open and run Pokemon Go to catch 'em. ... That's all. Wish succeed!