Reputation: 23808
I have a scenario where I am populating a combo box with the template names. Amongst the templates one would be a default template. I want to highlight the default template name when I populate the combo box (so that the user knows which one among the items is the default). Is it possible to do so? If yes how? I am using a Windows Form in C# 2.0.
Upvotes: 2
Views: 6542
Reputation: 158309
It depends a bit on how you want to hightlight the item. If you want to render the text of the default item in bold, you can achieve that like this (for this to work you need to set the DrawMode
of the ComboBox to OwnerDrawFixed
, and of course hook up the DrawItem event to the event handler):
I have populated the combobox with Template objects, defined like this:
private class Template
{
public string Name { get; set; }
public bool IsDefault { get; set; }
public override string ToString()
{
return this.Name;
}
}
...and the DrawItem event is implemented like this:
private void ComboBox_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index < 0)
{
return;
}
Template template = comboBox1.Items[e.Index] as Template;
if (template != null)
{
Font font = comboBox1.Font;
Brush backgroundColor;
Brush textColor;
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
backgroundColor = SystemBrushes.Highlight;
textColor = SystemBrushes.HighlightText;
}
else
{
backgroundColor = SystemBrushes.Window;
textColor = SystemBrushes.WindowText;
}
if (template.IsDefault)
{
font = new Font(font, FontStyle.Bold);
}
e.Graphics.FillRectangle(backgroundColor, e.Bounds);
e.Graphics.DrawString(template.Name, font, textColor, e.Bounds);
}
}
That should get you going in the right direction, I hope.
Upvotes: 8
Reputation: 5569
Set combo box's DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable. And, Override Combobox_MeasureItem() and Combobox_DrawItem() methods, to achieve this.
Upvotes: 0