c# - WinForms: Simplest way to change listbox text color on the fly? -


looking simple way add color text (or bold text) listbox item (the solutions i've seen in stackoverflow have seemed overly complicated needs).

i've been adding comments listbox via code:

listbox1.items.add("test complete!"); 

this line peppered throughout code. i'd love able modify occasional text color such line "test complete!" shows in green.

is there simple, on-the-fly solution this?

you can takes little bit of work setup, not complicated if looking setup font color or font.

you have add handler drawitem event.

this.listbox1.drawitem += new drawitemeventhandler(listbox1_drawitem); 

and here pretty simple handler looking for.

void listbox1_drawitem(object sender, drawitemeventargs e) {     graphics g = e.graphics;     dictionary<string, object> props = (this.listbox1.items[e.index] dictionary<string, object>);     solidbrush backgroundbrush = new solidbrush(props.containskey("backcolor") ? (color)props["backcolor"] : e.backcolor);     solidbrush foregroundbrush = new solidbrush(props.containskey("forecolor") ? (color)props["forecolor"] : e.forecolor);     font textfont = props.containskey("font") ? (font)props["font"] : e.font;     string text = props.containskey("text") ? (string)props["text"] : string.empty;     rectanglef rectangle = new rectanglef(new pointf(e.bounds.x, e.bounds.y), new sizef(e.bounds.width, g.measurestring(text, textfont).height));      g.fillrectangle(backgroundbrush, rectangle);     g.drawstring(text, textfont, foregroundbrush, rectangle);      backgroundbrush.dispose();     foregroundbrush.dispose();     g.dispose(); } 

and add items listbox can this.

this.listbox1.items.add(new dictionary<string, object> { { "text", "something, something"},                                                          { "backcolor", color.red },                                                          { "forecolor", color.green}}); this.listbox1.items.add(new dictionary<string, object> { { "text", "darkside!!" },                                                          { "backcolor", color.blue },                                                          { "forecolor", color.green },                                                          { "font", new font(new font("arial", 9), fontstyle.bold) } }); 

fairly simple think.

tada


Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -