c# - Convert string to Color -


i'm setting fields data via reflection. , have problem convert string color, convert.changetype(stringvalue,typeof(color)) throws exception. how can convert color in situation

        propertyinfo[] propertis = typeof(tentity).getproperties();         foreach (var attribute in element.attributes())         {             var property = propertis.where(x => x.name == attribute.name).firstordefault();             if (property != null)             {                 property.setvalue(somevariable, convert.changetype(attribute.value,property.propertytype), null);             }         } 

p.s color value not allways named color, color.fromname doesnt work

the color struct has typeconverter attribute on it, can this

var converter=typedescriptor.getconverter(property.propertytype); object convertedvalue=converter.convertto(attribute.value, property.propertytype); property.setvalue(somevariable, convertedvalue, null); 

there's more useful (in case) convertfromstring method:

var converter=typedescriptor.getconverter(property.propertytype); object convertedvalue=converter.convertfromstring(attribute.value); property.setvalue(somevariable, convertedvalue, null); 

a quick @ class in reflector suggests parse colors name or hex value, you're looking :-)

the system.componentmodel.typeconverter framework lot more flexible convert class


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -