I'm receiving an error, "unable to convert string to int?". Which I find odd, I was under the notion when you utilize PropertyInfo.SetValue
it should indeed attempt to use that fields type.
// Sample:
property.SetValue(model, null, null);
The above would attempt to implement default(T)
on the property according to PropertyInfo.SetValue
for the Microsoft Developer Network. However, when I implement the following code:
// Sample:
property.SetValue(model, control.Value, null);
The error bubbles, when I implement a string
for a property that should have an int?
, I was under the notion that it would attempt to automatically resolve the specified type. How would I help specify the type?
// Sample:
PropertyInfo[] properties = typeof(TModel).GetProperties();
foreach(var property in properties)
if(typeof(TModel).Name.Contains("Sample"))
property.SetValue(model, control.Value, null);
Any clarification and how to resolve the cast would be helpful. The sample has been modified for brevity, trying to provide relevant code.
You have to convert the control value to the type which the property is using Convert.ChangeType()
:
if(typeof(TModel).Name.Contains("Sample"))
property.SetValue(model, Convert.ChangeType(control.Value, property.PropertyType), null);
In your case it is Nullable
type (Nullable<int>
) so you have to do it different way as Convert.ChangeType()
in normal not works on Nullable types:
if(typeof(TModel).Name.Contains("Sample"))
{
if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
property.SetValue(model,Convert.ChangeType(control.Value, property.PropertyType.GetGenericArguments()[0]),null);
}
else
{
property.SetValue(model, Convert.ChangeType(control.Value, property.PropertyType), null);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With