Monday, July 04, 2005

.net Reflection Tip

To convert a string to its corresponding type use the following code snippet...
///
/// To get the underlying property type for the object
///

/// The object for which u r finding the property info.
/// The name of the property.. eg. For form object, say finding the Location property
/// The property value.
/// An object containing the underlying propertytype.
private object ConvertStringToPropertyType(object control,
string propertyName,
string val)
{
object result = null;

Type type = control.GetType();
PropertyInfo p = type.GetProperty(propertyName);
Type propertyType = p.PropertyType;

TypeConverter converter = TypeDescriptor.GetConverter(propertyType);
result = converter.ConvertFrom(val);

return result;
}

for eg. if you pass

No comments: