2

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!

Nidhi
  • 33
  • 1
  • 5

2 Answers2

1

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

Abishek
  • 11,191
  • 19
  • 72
  • 111
0

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

Francisco Aquino
  • 9,097
  • 1
  • 31
  • 37