Visual Studio .NET 2002.NET 1.0Visual Studio .NET 2003.NET 1.1IntermediateDevVisual StudioWindows.NETASP.NETC#
Picking a Color from a DropDownList






1.80/5 (6 votes)
Aug 10, 2004

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.
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
}
}
}
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
}
}