Reflection question: Dynamically populating an objects properties

M

MarkusJ_NZ

Hi, I am trying to dynamically populate an objects properties using
reflection.

Specifically, I have an object called the theObj and it has a number
of properties.

property is a PropertyInfo object

What I want to do is to be able to set the property value dynamically
which I am doing so using this line of code (Simplified version below)

property.SetValue(theObj, TextBox1.Text, null);

The above works fine if the property is of type String as the item
TextBox1.Text returns a string.

If however, the property is of type Int32, DateTime etc it fails...

What I need to do is to cast the value returned from the TextBox.Text
(string) to the data type the property expects..

something like this
(This does not work)

property.SetValue(theObj, ((property.GetType())TextBox1.Text), null);

Any help appreciated
Thanks
Markus
 
A

Alberto Poblacion

MarkusJ_NZ said:
something like this
(This does not work)

property.SetValue(theObj, ((property.GetType())TextBox1.Text), null);


IConvertible ic = (IConvertible)TextBox1.Text;
Type targetType = property.PropertyType;
property.SetValue(theObj, (ic.ToType(targetType,
CultureInfo.CurrentCulture)), null);
 
M

MarkusJ_NZ

IConvertible ic = (IConvertible)TextBox1.Text;
Type targetType = property.PropertyType;
property.SetValue(theObj, (ic.ToType(targetType,
CultureInfo.CurrentCulture)), null);

Thanks :)
 
M

Marc Gravell

For completeness - there is also something called a TypeConverter that
is accsesible from a PropertyDescriptor (which is very similar in
concept to a PropertyInfo); this allows for a much more context-
specific conversion, as you can specify the converter against
individual properties rather than the type. However, in most simple
cases a straight ToType will suffice.

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top