Is it possible to format a ComboBox item in C#? For example, how would I make an item bold, change the color of its text, etc.?
To make the text portion of a ComboBox non-editable, set the DropDownStyle property to "DropDownList". The ComboBox is now essentially select-only for the user. You can do this in the Visual Studio designer, or in C# like this: stateComboBox.
Just change the DropDownStyle to DropDownList . Or if you want it completely read only you can set Enabled = false , or if you don't like the look of that I sometimes have two controls, one readonly textbox and one combobox and then hide the combo and show the textbox if it should be completely readonly and vice versa.
Just to add to the answer supplied by Dan, don't forget that if you have bound the list to a Datasource, rather than just having a ComboBox with plain strings, you won't be able to redraw the entry by using combo.Items[e.Index].ToString()
.
If for example, you've bound the ComboBox to a DataTable, and try to use the code in Dan's answer, you'll just end up with a ComboBox containing System.Data.DataRowView
, as each item in the list isn't a string, it's a DataRowView.
The code in this case would be something like the following:
private void ComboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index == -1)
return;
ComboBox combo = ((ComboBox)sender);
using (SolidBrush brush = new SolidBrush(e.ForeColor))
{
Font font = e.Font;
DataRowView item = (DataRowView)combo.Items[e.Index];
if (/*Condition Specifying That Text Must Be Bold*/) {
font = new System.Drawing.Font(font, FontStyle.Bold);
}
else {
font = new System.Drawing.Font(font, FontStyle.Regular);
}
e.DrawBackground();
e.Graphics.DrawString(item.Row.Field<String>("DisplayMember"), font, brush, e.Bounds);
e.DrawFocusRectangle();
}
}
Where "DisplayMember"
is name of the field to be displayed in the list (set in the ComboBox1.DisplayMember
property).
As old as this post is, I found it useful as a starting point to search from but ended up having better results using the method shown here by @Paul.
Here is the code I used to conditionally make items in a combo box appear bold, I find that the answer marked correct for this question has strange behaviour - when you hover over an item is goes slightly bolder and stays that way as if it is being redrawn over. This code results in a more natural look:
private void ComboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index == -1)
return;
ComboBox combo = ((ComboBox)sender);
using (SolidBrush brush = new SolidBrush(e.ForeColor))
{
Font font = e.Font;
if (/*Condition Specifying That Text Must Be Bold*/)
font = new System.Drawing.Font(font, FontStyle.Bold);
e.DrawBackground();
e.Graphics.DrawString(combo.Items[e.Index].ToString(), font, brush, e.Bounds);
e.DrawFocusRectangle();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With