Stecya
Stecya

Reputation: 23266

Convert string to Color

I'm setting fields data via reflection. And I have a problem to convert string to Color, Convert.ChangeType(stringValue,typeof(Color)) throws Exception. How can i convert to Color in this 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 is not allways a named Color, so Color.FromName doesnt work

Upvotes: 1

Views: 3667

Answers (2)

Mitchel Sellers
Mitchel Sellers

Reputation: 63126

Based on the PS note, I don't think you are going to be able to handle this. The values have to be consistent, if it is a named color you can use Color.FromName, if it is a hex value you can use Color.FromArgb

If it isn't consistent, you are going to need to find a way to parse, determine the conversion, then complete it.

Upvotes: 1

Sean
Sean

Reputation: 62492

The Color struct has the TypeConverter attribute on it, so you can do something like this

var converter=TypeDescriptor.GetConverter(property.PropertyType);
object convertedValue=converter.ConvertTo(attribute.Value, property.PropertyType);
property.SetValue(someVariable, convertedValue, null);

There's also the more useful (in your case) ConvertFromString method:

var converter=TypeDescriptor.GetConverter(property.PropertyType);
object convertedValue=converter.ConvertFromString(attribute.Value);
property.SetValue(someVariable, convertedValue, null);

A quick look at the class in Reflector suggests that it will parse the colors by name or by their hex value, which is what you're looking for :-)

The System.ComponentModel.TypeConverter framework is a lot more flexible that the Convert class

Upvotes: 4

Related Questions