tags:

views:

47

answers:

4

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;
        UpdateData();
    }        
}

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.

A: 

You could just create a variable and assign the current setting to it at runtime, then just update the one variable whenever it's changed, after comparing it to the previous.

ManAmongHippos
A: 

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:

set
{
    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);
    }
}
ohadsc
+1  A: 

You could choose to implement settings like this:

class Settings
{
    public event EventHandler YearChanged;

    private int _year;

    public int Year
    {
        get { return _year; }
        set
        {
            if (_year != value)
            {
                _year = value;
                OnYearChanged(EventArgs.Empty);
            }
        }
    }

    protected virtual void OnYearChanged(EventArgs e)
    {
        if (YearChanged != null)
            YearChanged(this, e);
    }
}

Then you could register on the YearChanged event.

Pieter
+1  A: 

No, this isn't a good idea. The code is much too brittle. Catch this earlier. At the user interface level for example, whatever code you have that sets the setting value. It can fire the event and you'll know exactly what is getting modified. Or make an intermediate helper class.

Hans Passant