Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create colour picker with JavaScript or C#

In this article, we will learn today the process to create a colour picker utilizing JavaScript as well as C#.

The colour palette and colour picker features in the WebMatrix CSS editor make it easier to work with colours in CSS classes. These WebMatrix features let you make fine-tuned adjustments while ensuring that you’re using the latest CSS3 standards.

Using the colour palette

To use the colour picker, start by adding a CSS file to your site, or edit an existing one. When you’re ready to start adding colour, notice that a colour palette appears as you type your CSS:

Introduction

A handy control to have is a colour picker, which allows the user to select a colour from a list. It's possible to get quite fancy with this type of control. However, it can also be accomplished quite simply.

Here, we'll present a colour picker thereby making use of an owner-draw combo box. You can create an owner-draw combo box by placing a combo box on your form, setting the DrawMode property, and adding an event handler for the DrawItem event. However, to make the control easier to use in other projects, we'll place it within a custom control.

You could choose to create a user control and just drop a combo box on it. But since we are only modifying the behavior of a combo box and not adding any other components, inheriting from the ComboBox control just seems more straight forward.

The ColourPicker Control

Listing 1 shows my ColourPicker control. The code starts by declaring the ColourInfo class. This class defines the data for each colour contained in the list. It contains two properties: the colour text and the actual colour value.

The ColourPicker constructor sets a couple of property of the base ComboBox class. Since we aren't placing the combo box on a design surface, we are setting these properties programmatically. We set the DropDownStyle property to ComboBoxStyle.DropDownList. This specifies that the user cannot edit text in the control. We also set the DrawMode property to DrawMode.OwnerDrawFixed. This specifies that we will be drawing the list items ourselves, and that each item will be the same height. Finally, we add my custom OnDrawItem handler to the DrawItem event.

The user of the control can add any colours they like, but the AddStandardColours() method can be used to quickly add a number of popular colours. Note that if the user accesses the Items collection directly, nothing will stop them from adding objects of types other than ColourInfo. Ultimately, this will lead to exceptions or undefined behavior. An enhancement to the control might be to replace the Items collection with a type-safe collection. Until then, the programmer bears the responsibility to ensure only objects of type ColourInfo are added to the list of items.

The OnDrawItem() is my DrawItem event handler. This handler is called for each list item that needs to be rendered, including the item that appears in the edit portion of the combo box control. Given that this is the key method for customizing the control, it's really quite simple. It starts by clearing the background and then drawing a small box filled with the colour of the corresponding list item. Then it prints the name of the colour to the right of the box. Care is taken to correctly handle highlighted items, and items that require the focus rectangle.

Finally, we overrode the SelectedItem, SelectedText, and SelectedValue properties to make them type-safe, and just generally easier to work with when getting or setting colour values.

Listing 1: The ColourPicker Control with JavaScript

public partial class ColourPicker : ComboBox
{
    // Data for each colour in the list
    public class ColourInfo
    {
        public string Text { get; set; }
        public Colour Colour { get; set; }

        public ColourInfo(string text, Colour colour)
        {
            Text = text;
            Colour = colour;
        }
    }

    public ColourPicker()
    {
        InitializeComponent();

        DropDownStyle = ComboBoxStyle.DropDownList;
        DrawMode = DrawMode.OwnerDrawFixed;
        DrawItem += OnDrawItem;
    }

    // Populate control with standard colours
    public void AddStandardColours()
    {
        Items.Clear();
        Items.Add(new ColourInfo("Black", Colour.Black));
        Items.Add(new ColourInfo("Blue", Colour.Blue));
        Items.Add(new ColourInfo("Lime", Colour.Lime));
        Items.Add(new ColourInfo("Cyan", Colour.Cyan));
        Items.Add(new ColourInfo("Red", Colour.Red));
        Items.Add(new ColourInfo("Fuchsia", Colour.Fuchsia));
        Items.Add(new ColourInfo("Yellow", Colour.Yellow));
        Items.Add(new ColourInfo("White", Colour.White));
        Items.Add(new ColourInfo("Navy", Colour.Navy));
        Items.Add(new ColourInfo("Green", Colour.Green));
        Items.Add(new ColourInfo("Teal", Colour.Teal));
        Items.Add(new ColourInfo("Maroon", Colour.Maroon));
        Items.Add(new ColourInfo("Purple", Colour.Purple));
        Items.Add(new ColourInfo("Olive", Colour.Olive));
        Items.Add(new ColourInfo("Gray", Colour.Gray));
    }

    // Draw list item
    protected void OnDrawItem(object sender, DrawItemEventArgs e)
    {
        if (e.Index >= 0)
        {
            // Get this colour
            ColourInfo colour = (ColourInfo)Items[e.Index];

            // Fill background
            e.DrawBackground();

            // Draw colour box
            Rectangle rect = new Rectangle();
            rect.X = e.Bounds.X + 2;
            rect.Y = e.Bounds.Y + 2;
            rect.Width = 18;
            rect.Height = e.Bounds.Height - 5;
            e.Graphics.FillRectangle(new SolidBrush(colour.Colour), rect);
            e.Graphics.DrawRectangle(SystemPens.WindowText, rect);

            // Write colour name
            Brush brush;
            if ((e.State & DrawItemState.Selected) != DrawItemState.None)
                brush = SystemBrushes.HighlightText;
            else
                brush = SystemBrushes.WindowText;
            e.Graphics.DrawString(colour.Text, Font, brush,
                e.Bounds.X + rect.X + rect.Width + 2,
                e.Bounds.Y + ((e.Bounds.Height - Font.Height) / 2));

            // Draw the focus rectangle if appropriate
            if ((e.State & DrawItemState.NoFocusRect) == DrawItemState.None)
                e.DrawFocusRectangle();
        }
    }

    /// <summary>
    /// Gets or sets the currently selected item.
    /// </summary>
    public new ColourInfo SelectedItem
    {
        get
        {
            return (ColourInfo)base.SelectedItem;
        }
        set
        {
            base.SelectedItem = value;
        }
    }

Listing2: With C#

/// <summary>
    /// Gets the text of the selected item, or sets the selection to
    /// the item with the specified text.
    /// </summary>
    public new string SelectedText
    {
        get
        {
            if (SelectedIndex >= 0)
                return SelectedItem.Text;
            return String.Empty;
        }
        set
        {
            for (int i = 0; i < Items.Count; i++)
            {
                if (((ColourInfo)Items[i]).Text == value)
                {
                    SelectedIndex = i;
                    break;
                }
            }
        }
    }

    /// <summary>
    /// Gets the value of the selected item, or sets the selection to
    /// the item with the specified value.
    /// </summary>
    public new Colour SelectedValue
    {
        get
        {
            if (SelectedIndex >= 0)
                return SelectedItem.Colour;
            return Colour.White;
        }
        set
        {
            for (int i = 0; i < Items.Count; i++)
            {
                if (((ColourInfo)Items[i]).Colour == value)
                {
                    SelectedIndex = i;
                    break;
                }
            }
        }
    }
}

Result of article

Figure 1: Result of article

Conclusion

Go ahead and try to implement this of your own and learn how to create colour picker with JavaScript and C#. See you next time.



Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login