How to set and get property value?

WinForms - how to set property value in code and get bound control to update?

  • I have a WinForms app that contains several comboboxes, numericupdown controls and checkboxes. I also have a data class that exposes several properties and these controls are bound to those properties. Now I need the ability to restore the default values for each of these properties and have all of the bound controls update to reflect the change. For example, one of my comboBox controls is bound to an enum that contains (Red, Blue, Yellow and Green). The default value for this property is set to Blue in my data class constructor. When my app starts up, the combobox that's bound to this property correctly displays Blue as the default selected item. If a user were to select a different color and then decide that they want to revert back to the default color, I need a way to change the property value back to Blue and get the bound control to show that. I can set the property value in code but the problem is that my comboBox doesn't update to reflect the change. I'm guessing there's some kind of change notification mechanism that I need to implement in my data class but I'm not sure what that would be. Any ideas would be much appreciated. Thanks very much!

  • Answer:

    You'll need to implement INotifyProperyChanged in your data class like: public class Coloring : INotifyPropertyChanged { private string _name; public string Name { get { return _name; } set { if (_name != value) { _name = value; OnPropertyChanged("Name"); } } } // Do this for all your properties #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } #endregion }

user685869 at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

If you are using a BindingSource you can call its ResetBindings method. myBindingSource.ResetBindings(false);

Anders Forsgren

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.