Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Converting string to a Color ?

Status
Not open for further replies.

StevenK

Programmer
Jan 5, 2001
1,294
GB
Suppose I have a string :
str1 = "System.Drawing.Color.Yellow";
How can I convert this to a colour that I can use as a property against something like an item in a ListView?
For instance I want to set :
ListViewItem item = new ListViewItem("some text");
item.ForeColour = {code here to convert str1}
ListView1.Items.Add(item);

Can anyone help me with the missing bit ?
Thanks in advance ...
Steve
 
if you're using a listview couldn't you simply assign the item in the listview the color object as a value?

Gone looking for myself. Should I arrive before I'm back, keep me here.
 
You can do something using TypeConverter.ConvertFromString(ITypeDescriptorContext, string) and you have to unbox the returned object.
Assume you choose the color of the item to be added from a combobox or from somewhere as strings "Red", "Yellow", "Blue" .
I would write a function FormatItem() in which you can assign the right object using a swich case :

switch (colorOfItem.ToLower())
{
case "yellow":
item.ForeColour = System.Drawing.Color.Yellow;
break;
case "red":
item.ForeColour = System.Drawing.Color.Yellow;
break;
....

}

-obislavu-
 
The following function should do what you would like in a very generic way:
Code:
object StringToEnum (string val) {
   int last_dot = val.LastIndexOf('.');
   if (last_dot <= 0 || last_dot == val.Length - 1)
      throw new ArgumentException(&quot;Not a valid enumeration value.&quot;, &quot;val&quot;)
   return Enum.Parse(Type.GetType(val.Substring(0, last_dot)), val.Substring(last_dot + 1));
}
You will then have to cast to the specific enum type to set the value, so you could cut down on some work here by passing the type in and not getting it dynamically, or just shortcut to:
Code:
(System.Drawing.Color) Enum.Parse(typeof(System.Drawing.Color), val.Substring(val.LastIndexOf('.') + 1));

&quot;Programming is like sex, one mistake and you have to support it forever.&quot;

John

johnmc@mvmills.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top