469,267 Members | 1,007 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,267 developers. It's quick & easy.

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

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;
}
Nov 16 '05 #1
0 3696

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

2 posts views Thread by Zac | last post: by
2 posts views Thread by Jeff Bush | last post: by
5 posts views Thread by Brad | last post: by
3 posts views Thread by Matt Weaver | last post: by
13 posts views Thread by DaTurk | last post: by
15 posts views Thread by EDBrian | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.