Monday, January 4, 2010

Show Image in Combo Box


It is very easy to add images in combo box. Dot net provides an easy way to add image. here is an example code.


public static void BindTaskPriorityCombo(ComboBox priorityCombo, bool addEmpty)
{
priorityCombo.DrawMode = DrawMode.OwnerDrawVariable;
priorityCombo.DrawItem += new DrawItemEventHandler(priorityCombo_DrawItem);
priorityCombo.Items.Clear();

if (addEmpty)
{
priorityCombo.Items.Add("");
}

string[] priorities = {"High", "Medium", "Low"};
foreach (string priority in priorities )
{
priorityCombo.Items.Add(priority);
}
}

static void priorityCombo_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index >= 0)
{
ComboBox cmbPriority = sender as ComboBox;
string text = cmbPriority.Items[e.Index].ToString();
e.DrawBackground();

if (text.Length > 0)
{
string priority = text;
Image img = GetTaskPriorityImage(priority);

if (img != null)
{
e.Graphics.DrawImage(img, e.Bounds.X, e.Bounds.Y, 15, 15);
}
}

e.Graphics.DrawString(text, cmbPriority.Font, System.Drawing.Brushes.Black,
new RectangleF(e.Bounds.X + 15, e.Bounds.Y,
e.Bounds.Width, e.Bounds.Height));

e.DrawFocusRectangle();
}
}


public static Image GetTaskPriorityImage(string priority)
{
switch (priority)
{
case "High":
{
return Properties.Resources.High_Priority;
}
case "Low":
{
return Properties.Resources.Low_Priority;
}
case "Medium":
{
return Properties.Resources.Medium_Priority;
}

}

return null;

}

Call BindTaskPriorityCombo() method to to bind priority combo box. set priorityCombo.DrawMode = DrawMode.OwnerDrawVariable and register Draw item event of combo box using priorityCombo.DrawItem += new DrawItemEventHandler(priorityCombo_DrawItem) from drawing image in combo box item.

For more read my article:
http://www.codeproject.com/KB/applications/TaskManager.aspx