Greg
Greg

Reputation: 11480

Holy Reflection

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.

Upvotes: 5

Views: 129

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

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);

UPDATE:

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);
  }

Upvotes: 3

Related Questions