DataGridView Binding Problems

DataGridView Binding Problems

Old forum URL: forums.lhotka.net/forums/t/1114.aspx


MartinMason posted on Monday, September 04, 2006

We have what I would think would be a simple problem but I can't find a discussion on the topic anywhere.  On our form, we have an editable child collection that is bound to a DataGridView that allows additions and modifications within the grid.  One of the child properties is a quantity field that we would like to return a double.  With the attribute as a double, the following error is returned when changing the attribute value in the grid.

The following exception occurred in the DataGridView:

System.InvalidCastException: Unable to cast object of type 'system.Double' to type 'System.String'.

   at System.ComponentModel.ReflectPropertyDescriptor.SetValue(Object component, Object value) ....

Changing the attribute to return a string instead of a double resolves the problem so we have a work around.  Using the BindingSourceRefresh control did not resolve the problem either.

RockfordLhotka replied on Tuesday, September 05, 2006

I've used properties that return Double before with no problem. Can you walk through in the debugger to find the issue? Or look at the stack trace for the exception? My guess is that the exception is occuring in some code you don't realize is running, and which obviously is expecting a string rather than a double.

MartinMason replied on Tuesday, September 05, 2006

Found the line that caused the problem but still don't understand what's happening.  Here's the property definition:

public Double quantity{

   set{

      CanWriteProperty(true);

      if (_quantity != value){

         _quantity = value;

         PropertyHasChanged();

      }

   }

}

Removing the call to PropertyHasChanged resolved the problem as well.  Any ideas?

RockfordLhotka replied on Tuesday, September 05, 2006

PropertyHasChanged() triggers several activities as discussed in Chapters 3 and 7. Most notably, it triggers all your validation rule methods, so one of those could be the problem, and it raises the PropertyChanged event, so any event handler of that property could be the problem.

MartinMason replied on Tuesday, September 05, 2006

ID10T error. 

ValidationRules.AddRules(CommonRules.StringRequired, "quantity"); was the problem. 

Copyright (c) Marimer LLC