Viewing source for recipe0302cs.cs

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace AspNetCookbook
{
	/// <summary>

	/// Summary description for recipe0302cs.

	/// </summary>

	[ToolboxData("<{0}:RainbowLabel runat=server></{0}:RainbowLabel>")]
	public class RainbowLabel : System.Web.UI.WebControls.Label
	{
		public bool EnableRainbowMode
		{
			get { return (ViewState["EnableRainbowMode"] == null)? true : bool.Parse( ViewState["EnableRainbowMode"].ToString() ); }
			set { ViewState["EnableRainbowMode"] = value; }
		}

		protected override void Render(HtmlTextWriter output)
		{
			if (EnableRainbowMode)
				output.Write( ColorizeString(Text) );
			else
				output.Write(Text);
		}

		private string ColorizeString(string input)
		{
			System.Text.StringBuilder output = new System.Text.StringBuilder(input.Length);
			Random rand = new Random(DateTime.Now.Millisecond);

			for (int i = 0; i < input.Length; i++)
			{
				int red = rand.Next(0, 255);
				int green = rand.Next(0, 255);
				int blue = rand.Next(0, 255);

				output.Append("<font color=\"#");
				output.Append( Convert.ToString(red, 16) );
				output.Append( Convert.ToString(green, 16) );
				output.Append( Convert.ToString(blue, 16) );
				output.Append("\">");
				output.Append( input.Substring(i, 1) );
				output.Append("</font>");
			}

			return output.ToString();
		}
	}
}