65.9K
CodeProject is changing. Read more.
Home

Picking a Color from a DropDownList

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.80/5 (6 votes)

Aug 10, 2004

viewsIcon

62352

Picking a Color from a DropDownList.

Introduction

This small code samples shows how we can populate and select colors from the DropDownList control.

First of all, create a simple WebForm with a DropDownList, Button and Label controls.

Sample screenshot

Page Load Event Code:

In Page_Load, we will populate the DropDownList with the color names:

if(!Page.IsPostBack) 
{ 
    // Call Populate DropDownList
    PopulateDropDown();
}

PopulateDropDown Method Code:

public void PopulateDropDown() 
{
    // Make an instance of Color
    System.Drawing.Color c1 = new System.Drawing.Color();
    // Get the type of instance
    Type t = c1.GetType();
    foreach (PropertyInfo p1 in t.GetProperties())
    {
        ColorConverter d = new ColorConverter();
        try
        {
            // Add Items in DropDownList
            ddlList.Items.Add(p1.Name);
        }
        catch
        {
            // Catch exceptions here
        }
    }
}

Sample screenshot

Button Click event that changes the Color of Label control:

private void Button2_Click(object sender, System.EventArgs e)
{
    try
    {
        Color c = Color.FromName(ddlList.SelectedValue);
        Label1.Text = ddlList.SelectedValue;
        Label1.ForeColor = c;
    }
    catch(Exception ex)
    {
        throw; // TODO: handle this gracefully
    }
}

Sample screenshot