[Managed.Windows.Forms] Verify that DataMember is valid when setting DataSource
authorAlexander Köplinger <alex.koeplinger@outlook.com>
Fri, 20 Jun 2014 14:35:47 +0000 (16:35 +0200)
committerAlexander Köplinger <alex.koeplinger@outlook.com>
Fri, 20 Jun 2014 14:45:38 +0000 (16:45 +0200)
When DataMember is already set before DataSource we need to verify that it refers to a valid property in the DataSource setter, otherwise we'd get an exception in ResetList ().
This fixes the following failing tests: BindingSourceTest.DataMemberBeforeDataSource and BindingSourceTest.DataSourceAssignToDefaultType.

Commit licensed under MIT/X11.

mcs/class/Managed.Windows.Forms/System.Windows.Forms/BindingSource.cs

index 3e928459ba0a07803cfb928fd7a04cf758800480..a16a996355d4867ce3c803f219c156852e19956c 100644 (file)
@@ -207,6 +207,7 @@ namespace System.Windows.Forms {
                private void OnParentCurrencyManagerChanged (object sender, EventArgs args)
                {
                        // Essentially handles chained data sources (e.g. chained BindingSource)
+                       ResetDataMemberIfInvalid ();
                        ResetList ();
                }
 
@@ -349,6 +350,7 @@ namespace System.Windows.Forms {
 
                                        DisconnectDataSourceEvents (datasource);
                                        datasource = value;
+                                       ResetDataMemberIfInvalid ();
                                        ConnectDataSourceEvents (datasource);
                                        ResetList ();
 
@@ -454,6 +456,19 @@ namespace System.Windows.Forms {
                        }
                }
 
+               void ResetDataMemberIfInvalid ()
+               {
+                       if (datamember == String.Empty)
+                               return;
+
+                       // if dataMember doesn't refer to a valid property of dataSource, we need to reset it
+                       var property = ListBindingHelper.GetListItemProperties (datasource).Find (datamember, true);
+                       if (property == null) {
+                               datamember = String.Empty;
+                               OnDataMemberChanged (EventArgs.Empty);
+                       }
+               }
+
                // NOTE: Probably the parsing can be improved
                void ProcessSortString (string sort)
                {