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
Post a Comment