Tuesday, February 2, 2010

C# Changing Text font style (bold, color, family) in a Listbox or Combobox

My new question is how to set a new font type for a combobox or listbox in c sharp and... is easier than you are thinking.

First of all, we must set a new DrawMode Event for our Listbox

OurListBox.DrawMode = DrawMode.OwnerDrawFixed;
OurListBox.DrawItem += new DrawItemEventHandler(OurListBox1_DrawItem);

Now, when the Listbox is drawn, the application will call the function OurListBox1_DrawItem and is here when we change the font style.

private void OurListBox1_DrawItem (object sender, DrawItemEventArgs e)
{
e.DrawBackground();
e.Graphics.DrawString(OurListBox.Items[e.Index].ToString(), new Font("Microsoft Sans Serif", 8, FontStyle.Regular), Brushes.DarkBlue, e.Bounds);
e.DrawFocusRectangle();
}


and ... done it!, You will have yours list items in DarkBlue color.

Question? hehehe.

Greetings