It looks to me that the problem you're running into is your
DataRow
holding an
Int32
and you want to assign that to a
Decimal
using the
SetValue
method of
PropertyInfo
.
To do that you only need to use the
Convert.ChangeType
method, it'll handle the cast for you.
Like in this example application (i've stripped
DataRow
s and
DbNull
s out for simplicity, but the problem is the same):
using System;
using System.Collections.Generic;
using System.Reflection;
namespace ConsoleApplication14
{
public class MyObject
{
public int Int { get; set; }
public double Double { get; set; }
public float Float { get; set; }
public decimal Decimal { get; set; }
public string String { get; set; }
}
class Program
{
static void Main(string[] args)
{
IDictionary<string, object> values = new Dictionary<string, object>();
values["Int"] = 1;
values["Double"] = 123.0f;
values["Float"] = 120.0d;
values["Decimal"] = 2;
values["String"] = "0";
MyObject o = new MyObject();
foreach (string name in values.Keys)
{
PropertyInfo property = o.GetType().GetProperty(name);
property.SetValue(o, Convert.ChangeType(values[name],
property.PropertyType), null);
}
}
}
}
Hope this helps,
Fredrik