Using typeConverter

Hi,

In this example I’ll show you how you can use the typeConverter class to convert one type to another. For example you can use the typeConverter to convert a string to a color. You can use it for about any type.

I first go through the Color enumeration and afterwards I change the color of a label when a certain color is selected. Here is the code.

string[] colorArray; if (!this.IsPostBack) { //get the names from the Color enumeration colorArray = Enum.GetNames(typeof(KnownColor)); //Bind the array to the list lstColors.DataSource = colorArray; lstColors.DataBind(); } //Convert the string to the color //Here we need to first set the correct converter and then convert it. this.lblTest.BackColor = (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString(lstColors.SelectedItem.Text);

Oh yea, don’t forget to add this namespace:

using System.ComponentModel;


No comments yet. Be the first.

Leave a reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word