User control based on System.Web.UI.WebControls.Label (C#)
<%@ Page Language="C#" %>
<%@ Register TagPrefix="Control" Namespace="Control" Assembly="Control" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>Custom Controls - Extending Existing Web Controls</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<Control:RainbowLabel text="This is a rainbow colored test string" runat="server" /><br/>
<Control:RainbowLabel EnableRainbowMode="false" text="This is a test string" runat="server" />
</form>
</body>
</html>
File: Control.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
namespace Control
{
[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();
}
}
}
Related examples in the same category