Search code examples
winformsdatatabledatagridvieweventhandler

WinForms: Why does databinding break if adding an event with "Changed" suffix?


There is a Model class with public DataTable variable named "RelatedPrograms". It is used as a source for a DataGridView control in a UserControl class via databinding:

dataGridView.DataBindings.Add("DataSource", Model, nameof(Model.RelatedPrograms), false, DataSourceUpdateMode.OnPropertyChanged);

Now if I introduce a new event field named "RelatedProgramsChanged" to the Model class

public event EventHandler<EventArgs> RelatedProgramsChanged;

databinding stops working and DataGridView won't be refreshed with data from DataTable. However columns are shown properly. What is causing this? All works well as long as the variable does not end with -Changed and is not defined as an event.


Solution

  • If you are defining RelatedProgramsChanged, you should also fire that event when the property value changes. You have not shown enough code to pinpoint the failure point in your implementation.

    The PropertyNameChanged event was the way to signal a change before the introduction of the INotifyPropertyChanged Interface. For more information see: Property-Changed Events.

    From the Remarks section of INotifyPropertyChanged:

    For change notification to occur in a binding between a bound client and a data source, your bound type should either:

    • Implement the INotifyPropertyChanged interface (preferred).

    • Provide a change event for each property of the bound type.

    Do not do both.

    This event along with the ShouldSerializePropertyName and ResetPropertyName (see: Defining Default Values with the ShouldSerialize and Reset Methods) methods are retrieved by the property descriptor used by the WinForm binding mechanism. You can inspect the propery descriptor code at ReflectPropertyDescriptor and read the comments to learn more.