PeteT PeteT - 1 year ago 93
C# Question

.NET user settings event handlers

I am trying to use the built in .NET application settings. So for instance I have a User setting of year.

If the end user changes the setting in the program I need to respond by refreshing the data displayed.

I currently have code like below to do this:

Settings.Default.PropertyChanged += SettingsChanged;

//on year change clear out the grid and update the data
private void SettingsChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
if (e.PropertyName == "year")
grdStudentCourseSearch.DataSource = null;
grdStudentCourseSearch.DataMember = null;

As you can see their seems to only be an event handler for all the settings and I am having to use e.PropertyName to compare a string to see which property has changed. Is there a better way to do this? Potentially if I change property names later this could be forgotten.

Answer Source

I believe there isn't a better way (using the generated Settings class), due to the implementation of the Settings Class Consider the generated class code for a simple string setting:

public string Test {
    get {
        return ((string)(this["Test"]));
    set {
        this["Test"] = value;

As you can see, it uses the indexer with a string value - you don't have any specialized TestChanged event or some such. The call to OnPropertyChanged is in the indexer setter:

    SettingChangingEventArgs e = new SettingChangingEventArgs(propertyName, base.GetType().FullName, this.SettingsKey, value, false);
    this.OnSettingChanging(this, e);
    if (!e.Cancel)
        base[propertyName] = value;
        PropertyChangedEventArgs args2 = new PropertyChangedEventArgs(propertyName);
        this.OnPropertyChanged(this, args2);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download