0

I have been using the following Code to set Class Properties using Relection

MyClasss c = new MyClass(id);
prop = c.GetType().GetProperty(field);
prop.SetValue(c, Convert.ChangeType(value, prop.PropertyType), null);

The value is taken from a DataGridView and triggered by the CellEndEdit event and so the value input by the user can be any of large number of properties and types.

Sometimes the Convert.ChangeType works successfully, but other times I get an Invalid Cast error.

For example if the property type is (decimal?) [a nullable decimal] I get the error.

[EDIT]

As a bit more background to what I am doing, the DataGridView contains information regarding what recent changes Users have made to the data in SQL server. It contains a list of changes, showing table, field, new value and old value together with details of who made the changes and when. There is an option to Revert if the manager disagrees with one of the changes. So when an item from the list is selected, my code needs to look up the appropriate table and field, and set the current value back to the stored oldvalue. It's an audit control facility which the client specifically wanted as a DataGrid.

The problem is that due to the number of fields displayed on the datagrid, the type of data could be anything, and is not know until runtime. I honestly don't know how I could use DataBinding in these circumstances, but if someone still believes that is a better option than Reflection could they perhaps point me in the right direction please.

PJW
  • 5,197
  • 19
  • 60
  • 74
  • Why don't you use data binding? This is what it is intended for. The code you wrote is the re-inventing the wheel. – Dennis Nov 13 '13 at 05:50
  • The input actually comes from a DataGridView which shows data from a number of different tables, and there are many properties and types covered by it. I'm not sure how I would use DataBinding in those circumstances. – PJW Nov 13 '13 at 05:56
  • 1
    So your problem can be broken down to `Convert.ChangeType("12", typeof(decimal?))` ? – Ilya Ivanov Nov 13 '13 at 05:57
  • I'm **sure**, that data binding was created exactly for these purposes. – Dennis Nov 13 '13 at 05:57
  • Yes Ilya, but the property type is not known until runtime and may not be (decimal?). – PJW Nov 13 '13 at 05:59
  • what the value variable? – Grundy Nov 13 '13 at 06:01
  • 1
    Treat nullables a little bit different, see http://stackoverflow.com/questions/3531318/convert-changetype-fails-on-nullable-types – Konrad Kokosa Nov 13 '13 at 06:37

1 Answers1

2

The value of types accepted by Convert.ChangeType must implement IConvertible. It's obvious that your are converting arbitrary types, for those do not not implement the interface, you'll get the invalid cast exception.

See: Convert.ChangeType

Ken Kin
  • 4,503
  • 3
  • 38
  • 76