By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,296 Members | 1,469 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,296 IT Pros & Developers. It's quick & easy.

Reflection question: Dynamically populating an objects properties

P: n/a
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

Nov 5 '07 #1
Share this Question
Share on Google+
3 Replies


P: n/a
"MarkusJ_NZ" <Ma*******@gmail.comwrote in message
news:11**********************@v29g2000prd.googlegr oups.com...
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);
Nov 6 '07 #2

P: n/a
On Nov 6, 5:21 pm, "Alberto Poblacion" <earthling-
quitaestoparacontes...@poblacion.orgwrote:
"MarkusJ_NZ" <Markus...@gmail.comwrote in message

news:11**********************@v29g2000prd.googlegr oups.com...
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);
Thanks :)

Nov 6 '07 #3

P: n/a
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

Nov 6 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.