Question

I need to convert a string which has the name of a color (e.g. "Red") to an object of System.Windows.Media.Color.

I am using the following code:

using System.ComponentModel;

TypeConverter tc = new TypeConverter();
Color bgColor = (Color)(tc.ConvertFrom((li["Background_x0020_Color"].ToString())));

The code builds successfully, but throws a runtime exception : "ConvertFrom not implemented in base TypeConverter."

Any help is greatly appreciated. Thanks!

Was it helpful?

Solution

Try this

Color c;
Type colorType = (typeof(System.Windows.Media.Colors));
if (colorType.GetProperty(slist.color) != null)
{
    object o = colorType.InvokeMember("Red", BindingFlags.GetProperty, null, null, null);
    if (o != null)
    {
        c = (Color)o;
    }
    else
    {
        c = Colors.Black;
    }
}
else
{
    c = Colors.Black;
}
Brush color = new SolidColorBrush(c);

http://jyothsnag.blogspot.in/2011/04/convert-string-to-color-object-in.html

OTHER TIPS

The error means that TypeConverter is too low level to do that, it doesn't even have code (called implementation) inside the ConvertFrom method, use System.Web.UI.WebControls.WebColorConverter

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top