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

Fix network printer error 0x0000709

When printing in the network, sometimes you see the error "Operation could not be completed (error 0x00000709). Double click the printer name and make sure that the printer is connected to the network".  Here we show how to fix the error: Open Windows Control Panel Open Credential Manager Choose Windows Credentials Click Add a Windows credential Internet or network address: input the computer name which share the printer User name: input "guest" Password: leave it blank Then click OK and reconnect the shared printer Do not need: uninstall Windows updates; change Windows registry... This maybe applied for error: 0x00000005, 0x0000011b... Watch the step by step video on here: