Click here to Skip to main content
14,693,352 members
Articles » Web Development » Custom Controls » General
Posted 20 Jul 2008


75 bookmarked

ASP.NET Color Picker Web Server Control

Rate me:
Please Sign up or sign in to vote.
4.85/5 (35 votes)
6 Apr 2010CPOL
An ASP.NET color picker web server control


It is difficult to find a decent color picker control for ASP.NET. However, there are plenty of pure JavaScript color picker controls. I decided to take one of them and convert it into an ASP.NET web server control. As a base, I took the dhtmlgoodies advanced color picker.

Project Setup

First, let's do New Project ->ASP.NET Server Control. By default, the name of the project would be the same as the name of the default namespace. I called my project WebControls, and renamed ServerControl1.cs to ColorPicker.cs. I changed default namespace to Karpach.WebControls, as well as assembly name. Then, I added to the project the images, JavaScript, and styles supplied by dhtmlgoodies.


Then, I clicked on each file's properties and changed the Build Action from Content to Embedded Resource. I also renamed some of the files.


I registered all the resources like this:

[assembly: System.Web.UI.WebResource("Karpach.WebControls.Images.SliderHandle.gif",
[assembly: System.Web.UI.WebResource("Karpach.WebControls.Images.TabCenterActive.gif",
[assembly: System.Web.UI.WebResource("Karpach.WebControls.Images.TabLeftActive.gif",
[assembly: System.Web.UI.WebResource("Karpach.WebControls.Images.TabLeftInactive.gif",
[assembly: System.Web.UI.WebResource("Karpach.WebControls.Images.TabRightActive.gif",
[assembly: System.Web.UI.WebResource("Karpach.WebControls.Images.TabRightInactive.gif",
[assembly: System.Web.UI.WebResource("Karpach.WebControls.Images.ColorPickerIcon.jpg",

[assembly: System.Web.UI.WebResource("Karpach.WebControls.Styles.ColorPicker.css",

[assembly: System.Web.UI.WebResource("Karpach.WebControls.Javascript.ColorPicker.js",

As you might have noticed, System.Web.UI.WebResource, the first parameter has the following signature:

[Assembly Name].[Folder].[File Name]

This is very important, since it is not documented even in MSDN.


In order to enable Validators for your control, you need to specify ValidationProperty attribute of your server control class.


I modified ToolboxData to look like this:

[ToolboxData("<{0}:ColorPicker runat="server">")]

Next, I wanted a custom icon in the Visual Studio Toolbox. After ToolboxData, I added the following line:


where the first parameter is the type of the control and the second parameter is the icon file name used in AssemblyInfo.cs.

Originally color picker had two JavaScript files: color_functions.js and js_color_picker_v2.js. I combined them in one file, ColorPicker.js. Those files had a bunch of functions. I combined everything in one JavaScript class, exposed some public properties and one public function ShowColorPicker.

function ColorPicker(options)
    // Public properties
    this.FormWidgetAmountSliderHandleImage = options.FormWidgetAmountSliderHandleImage;
    this.TabRightActiveImage = options.TabRightActiveImage;
    this.TabRightInactiveImage = options.TabRightInactiveImage;
    this.TabLeftActiveImage = options.TabLeftActiveImage;
    this.TabLeftInactiveImage = options.TabLeftInactiveImage;
    this.AutoPostBack = options.AutoPostBack;
    this.AutoPostBackReference = options.AutoPostBackReference;
    this.PopupPosition = options.PopupPosition;

    // Public methods

    this.ShowColorPicker = function(inputObj, formField)
	// Private variables
	// ....
	// Private functions
    // ....

After some feedback, I had to fix JavaScript in order to support ASP.NET AJAX UpdatePanel and ModalPopup extender.

Then, I needed to load the stored resources from the DLL into JavaScript class. The best event for this is OnPreRender:

// Javascript
string colorFunctions = Page.ClientScript.GetWebResourceUrl(typeof(ColorPicker),
Page.ClientScript.RegisterClientScriptInclude("ColorPicker.js", colorFunctions);

// Create ColorPicker object
string script = string.Format(@"
var colorPicker_{0} = new ColorPicker({{
FormWidgetAmountSliderHandleImage : '{1}',
TabRightActiveImage : '{2}',
TabRightInactiveImage : '{3}',
TabLeftActiveImage : '{4}',
TabLeftInactiveImage : '{5}',
AutoPostBack : {6},
AutoPostBackReference : ""{7}"",
PopupPosition : {8}
", ClientID
 , Page.ClientScript.GetWebResourceUrl(typeof(ColorPicker), 
 , Page.ClientScript.GetWebResourceUrl(typeof(ColorPicker), 
 , Page.ClientScript.GetWebResourceUrl(typeof(ColorPicker), 
 , Page.ClientScript.GetWebResourceUrl(typeof(ColorPicker), 
 , Page.ClientScript.GetWebResourceUrl(typeof(ColorPicker), 
 , AutoPostBack?"true":"false"
 , Page.ClientScript.GetPostBackEventReference(this,"")
 , (int)PopupPosition

	String.Format("InitColorPicker_{0}", ClientID), script, true);
if (!DesignMode && Page.Header != null)

Where RegisterCSSInclude is the following helper method:

private void RegisterCSSInclude(Control target)
    // CSS                   
    bool linkIncluded = false;
    foreach (Control c in target.Controls)
        if (c.ID == "ControlPickerStyle")
            linkIncluded = true;
    if (!linkIncluded)
        HtmlGenericControl csslink = new HtmlGenericControl("link");
        csslink.ID = "ControlPickerStyle";
        csslink.Attributes.Add("href", Page.ClientScript.GetWebResourceUrl
	(typeof(ColorPicker), "Karpach.WebControls.Styles.ColorPicker.css"));
        csslink.Attributes.Add("type", "text/css");
        csslink.Attributes.Add("rel", "stylesheet");
        csslink.EnableViewState = false;

Then I overrode the Render event of WebControl class in order to render the control HTML.

using (PlaceHolder plh = new PlaceHolder())
    if (DesignMode || Page.Header == null)
    Table table = new Table();
    table.CellPadding = 0;
    table.CellSpacing = 0;
    table.Rows.Add(new TableRow());
    table.Rows[0].Cells.Add(new TableCell());
    table.Rows[0].Cells.Add(new TableCell());
    table.Rows[0].Cells.Add(new TableCell());
    table.Rows[0].Cells[1].Style.Add(HtmlTextWriterStyle.PaddingRight, "5px");
    HtmlGenericControl txt = new HtmlGenericControl("input");
    txt.EnableViewState = false;
    txt.Attributes.Add("maxlength", "15");
    txt.Attributes.Add("size", "15");
    txt.Attributes.Add("value", Color);
    txt.Attributes.Add("id", ClientID);
    txt.Attributes.Add("name", UniqueID);
    txt.Attributes.CssStyle.Value = "height:17px;padding:2px;";
    HtmlGenericControl colorBar = new HtmlGenericControl("div");
    colorBar.EnableViewState = false;
    colorBar.Attributes.CssStyle.Add(HtmlTextWriterStyle.Height, "21px");
    colorBar.Attributes.CssStyle.Add(HtmlTextWriterStyle.Width, "5px");
    colorBar.Attributes.CssStyle.Add("border", "solid 1px #7f9db9");
    colorBar.Attributes.CssStyle.Add(HtmlTextWriterStyle.BackgroundColor, Color);
    HtmlInputImage btn = new HtmlInputImage();
    btn.Src = Page.ClientScript.GetWebResourceUrl(typeof(ColorPicker), 
    btn.Attributes.Add("onclick", string.Format("colorPicker_{0}.ShowColorPicker
	(this,document.getElementById('{1}'));return false;", ClientID, ClientID));
    btn.Attributes.CssStyle.Add(HtmlTextWriterStyle.ZIndex, "1");
    HtmlGenericControl container = new HtmlGenericControl("div");
    container.EnableViewState = false;
    container.Attributes.CssStyle.Add(HtmlTextWriterStyle.Position, "static");
    container.Attributes.CssStyle.Add(HtmlTextWriterStyle.Display, "block");

There are a few ways how you can save postback value of color picker. However I think the best way is to implement IPostBackDataHandler interface.

public bool LoadPostData(string postDataKey,NameValueCollection postCollection)
    String presentValue = Color;
    String postedValue = postCollection[postDataKey];

    if (presentValue == null || !presentValue.Equals(postedValue))
        Color = postedValue;
        return true;
    return false;

public virtual void RaisePostDataChangedEvent()

public void OnColorChanged(EventArgs e)
    if (ColorChanged != null)
        ColorChanged(this, e);

LoadPostData method will be called during each postback, when postback form has token with key this.UniqueID. As you can see above, the rendered input tag has name attribute this.UniqueID.

ColorPicker properties are stored in ControlState by overriding LoadControlState and SaveControlState:

protected override void LoadControlState(object savedState)
    Color = (string)(savedState as object[])[0];
    AutoPostBack = (bool)(savedState as object[])[1];
    PopupPosition = (PopupPosition)(savedState as object[])[2];

protected override object SaveControlState()
    object []saveState = new object[3];
    saveState[0] = Color;
    saveState[1] = AutoPostBack;
    saveState[2] = PopupPosition;
    return (object)saveState;

You need to invoke the RegisterRequiresControlState method to register control for participation in control state, otherwise LoadControlState and SaveControlState won't fire.

protected override void OnInit(EventArgs e)


Now, the final touch: Minification of JavaScript and CSS. I used Yahoo YUI compressor and Microsoft MSBuild. Here is the final MSbuild file:

<?xml version="1.0" encoding="utf-8" ?>
<Project ToolsVersion="3.5" xmlns="">

  <Target Name="Compress">

    <Message Text="Create temp files ..." />
    <Copy SourceFiles=".\$(ProjectName)\Javascript\ColorPicker.js"

    <Copy SourceFiles=".\$(ProjectName)\Styles\ColorPicker.css"

    <Exec Command=
       "java -jar yuicompressor-2.4.2.jar --type js .\$(ProjectName)\
       Javascript\ColorPicker.js.full >.\$(ProjectName)\Javascript\ColorPicker.js"/>

    <Exec Command=
       "java -jar yuicompressor-2.4.2.jar --type css .\$(ProjectName)\Styles\
       ColorPicker.css.full >.\$(ProjectName)\Styles\ColorPicker.css"/>
  <Import Project=".\References\MSBuild.Community.Tasks.targets" />
  <Target Name="Build" DependsOnTargets="Compress">

    <Message Text="Building Project" />
    <MSBuild Projects="./$(ProjectName)/$(ProjectName).sln"

        Properties="Configuration=Release;Platform=Any CPU" />    

Now you even don't need Visual Studio to compile DLL. All that you need is .NET 2.0 installed and then the following console script will do the compilation:

%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\MSBuild.exe  Build.proj /t:Build

Per requests below, I added PopupPosition property, so you can specify position of ColorPicker popup (top left, top right, bottom left, bottom right - default).

I also added AutoPostBack property and ColorChanged event.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Viktar Karpach
Web Developer comScore
United States United States
No Biography provided

Comments and Discussions

GeneralRe: Problem in Multiview Pin
gchq22-Jan-09 5:53
Membergchq22-Jan-09 5:53 
GeneralRe: Problem in Multiview Pin
Viktar Karpach22-Jan-09 18:54
MemberViktar Karpach22-Jan-09 18:54 
GeneralRe: Problem in Multiview Pin
gchq23-Jan-09 4:34
Membergchq23-Jan-09 4:34 
GeneralProblem in saving color using color picker Pin
NidhiKanu9-Jan-09 0:17
professionalNidhiKanu9-Jan-09 0:17 
GeneralRe: Problem in saving color using color picker Pin
Viktar Karpach10-Jan-09 10:38
MemberViktar Karpach10-Jan-09 10:38 
GeneralRe: Problem in saving color using color picker Pin
NidhiKanu11-Jan-09 20:44
professionalNidhiKanu11-Jan-09 20:44 
GeneralRe: Problem in saving color using color picker Pin
gchq19-Jan-09 14:38
Membergchq19-Jan-09 14:38 
GeneralNice work! Pin
George Steven16-Dec-08 22:18
MemberGeorge Steven16-Dec-08 22:18 
GeneralFirefox? issue Pin
Member 431275217-Nov-08 12:22
MemberMember 431275217-Nov-08 12:22 
GeneralRe: Firefox? issue Pin
Viktar Karpach17-Nov-08 19:20
MemberViktar Karpach17-Nov-08 19:20 
GeneralPls Help Me Pin
farzaneh ansari15-Nov-08 3:56
Memberfarzaneh ansari15-Nov-08 3:56 
GeneralRe: Pls Help Me Pin
Viktar Karpach15-Nov-08 13:26
MemberViktar Karpach15-Nov-08 13:26 
Generalthanks alot Pin
farzaneh ansari15-Nov-08 21:44
Memberfarzaneh ansari15-Nov-08 21:44 
QuestionHow to use the slider Pin
Member 431275210-Nov-08 13:41
MemberMember 431275210-Nov-08 13:41 
AnswerRe: How to use the slider Pin
Member 431275210-Nov-08 13:43
MemberMember 431275210-Nov-08 13:43 
GeneralUsing the control within SharePoint Pin
Menon Hari17-Oct-08 9:12
MemberMenon Hari17-Oct-08 9:12 
GeneralRe: Using the control within SharePoint Pin
Viktar Karpach17-Oct-08 14:48
MemberViktar Karpach17-Oct-08 14:48 
GeneralUpdated value Pin
Member 106667515-Oct-08 23:20
MemberMember 106667515-Oct-08 23:20 
GeneralRe: Updated value Pin
Viktar Karpach17-Oct-08 15:08
MemberViktar Karpach17-Oct-08 15:08 
Answerthank you very much Pin
Howdy Nun9-Oct-08 1:10
MemberHowdy Nun9-Oct-08 1:10 
Generalproblem resolved: how to use the control programatically Pin
pixel3cs7-Sep-08 2:07
Memberpixel3cs7-Sep-08 2:07 
GeneralRe: problem resolved: how to use the control programatically Pin
Viktar Karpach7-Sep-08 15:00
MemberViktar Karpach7-Sep-08 15:00 
QuestionRe: problem resolved: how to use the control programatically Pin
Goslow13-Oct-08 5:55
MemberGoslow13-Oct-08 5:55 
AnswerRe: problem resolved: how to use the control programatically Pin
Viktar Karpach13-Oct-08 14:22
MemberViktar Karpach13-Oct-08 14:22 
GeneralRe: problem resolved: how to use the control programatically Pin
Goslow13-Oct-08 22:02
MemberGoslow13-Oct-08 22:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.