Friday, October 24, 2008

How to draw a color list ComboBox


In Windows Forms project, ComboBox is one of the most common controls that we have ever used. Microsoft .Net control library offers a lot of events and methods that let you custom your own control’s UI as well as its function. Now I want to introduce you a way to custom a color ComboBox which can show you a colorful dropdown list.

In this example, first you should set the DrawMode property of your ComboBox to DrawMode.OwnerDrawFixed and DropDownStyle property to ComboBoxStyle.DropDownList. Then you can handle the DrawItem event to draw each item base on the ColorList (a list which contain all color you want to draw).

Here is the code of your color list ComboBox
public class ColorComboBox : System.Windows.Forms.ComboBox
{
private List< Color > _colorList;

public ColorComboBox()
{
_colorList = new List< Color >();
this.DrawMode = DrawMode.OwnerDrawFixed;
this.DropDownStyle = ComboBoxStyle.DropDownList;
this.DrawItem += new DrawItemEventHandler(ColorComboBox_DrawItem);
}

public ColorComboBox(List< Color > colorList)
{
_colorList = colorList;
this.DrawMode = DrawMode.OwnerDrawFixed;
this.DropDownStyle = ComboBoxStyle.DropDownList;

for (int i = 0; i < colorList.Count; i++)
{
this.Items.Add("");
}
this.SelectedIndex = 0;
this.DrawItem += new DrawItemEventHandler(ColorComboBox_DrawItem);
}

void ColorComboBox_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index >= 0)
{
Graphics g = e.Graphics;
Brush brush = new SolidBrush(_colorList[e.Index]);
Rectangle rec = e.Bounds;
g.FillRectangle(brush, rec);
}
}

public List< Color > ColorList
{
get { return _colorList; }
set
{
_colorList = value;
for (int i = 0; i < _colorList.Count; i++)
{
this.Items.Add("");
}
this.SelectedIndex = 0;
}
}
}

Let us test it on a Windows Form application
public partial class Form1 : Form
{
private ColorComboBox colorCmb;

public Form1()
{
InitializeComponent();

List< Color > colorList = new List< Color >();
colorList.Add(Color.Black);
colorList.Add(Color.Blue);
colorList.Add(Color.Yellow);
colorList.Add(Color.Green);
colorList.Add(Color.Red);
colorList.Add(Color.Pink);

colorCmb = new ColorComboBox();
colorCmb.ColorList = colorList;
colorCmb.Location = new Point(50, 50);
this.Controls.Add(colorCmb);
}
}

Then you can run your code to see the effect. Click the dropdown button of that ComboBox, you can see the color that we have put in the ColorList. Wish you can enjoy this.

No comments: