dynamic properties - SetValue(), casting value to type prob

  • Thread starter Thread starter Oliver
  • Start date Start date
O

Oliver

hi -

I'm trying to set Properties dynamically (web forms).

The problem is that I can't seem to set the property value based on a
string - even though I know the Type of the Property.

I seem to have to convert the string to the correct Type for the
property before I set it's value (using SetValue) - this is where I'm
having trouble.

converting the type is easy for Color, int, boolean etc - but I'm a
bit stuck on others.

is there an existing routine for converting a string to a known type?
- surely Visual Studio does this in the Forms Designer...


example:

PropertyInfo propertyInfo =
myControl.GetType().GetProperty(propertyName);
Type propertyType = propertyInfo.PropertyType;

// aaarg - need this line to do my own Type conversion
object propertyConverted = convertType(propertyValue, propertyType);

// set the property - works fine *if* convertType worked
propertyInfo.SetValue(Label1, propertyConverted, null);



private object convertType(string data, Type type)
{
if (type == typeof(bool))
return bool.Parse(data);

if (type == typeof(System.Drawing.Color))
return Color.FromName(data);

if (type.IsEnum == false)
return System.Enum.Parse(type, data, true);

if (type == typeof(int))
return System.Int32.Parse(data);

return data;
}
 
Back
Top