c# - All listbox items colored instead of one by one -
when listbox's drawitem
event fired. iterate through items , if each item's text meets condition, background color green , if not, yellow.
with following code, items same color. not @ programming graphics in c sharp
guess.
private void listboxyourselection_drawitem(object sender, drawitemeventargs e) { listbox lst = (listbox)sender; foreach(string item in lst.items) { color col = new color(); e.drawbackground(); e.drawfocusrectangle(); if (conditionistrue) col = color.green; else col = color.yellow; e.graphics.drawrectangle(new pen(col), e.bounds); e.graphics.fillrectangle(new solidbrush(col), e.bounds); if (e.index >= 0) { e.graphics.drawstring(lst.items[e.index].tostring(), e.font, new solidbrush(color.black), e.bounds, stringformat.genericdefault); } } }
the mistake indeed iterate on items in listbox
.
you don't need care other item
since drawitem
method doing you! called separately each item in listbox, whenever system thinks necessary..
all need take care of choosing right color, font, text
etc one item
painting in current call.
you can identify item being painted looking @ e.index
parameter.
a modified version this:
private void listbox1_drawitem(object sender, drawitemeventargs e) { // testing turn on every other item; // want use way decide..!! bool conditionistrue = e.index % 2 == 0; bool selected = listbox1.selectedindex == e.index; color col = new color(); if (conditionistrue) col = selected ? systemcolors.hottrack : color.palegreen; else col = selected ? systemcolors.hottrack : color.gold; e.drawbackground(); // not needed e.drawfocusrectangle(); // not needed either using (pen pen = new pen(col)) using (solidbrush brush = new solidbrush(col)) { e.graphics.drawrectangle(new pen(col), e.bounds); e.graphics.fillrectangle(new solidbrush(col), e.bounds); } if (e.index >= 0) { e.graphics.drawstring(listbox1.items[e.index].tostring(), e.font, selected? brushes.white:brushes.black, e.bounds, stringformat.genericdefault); } } }
obviously conditionistrue should set in other way in code! if method may want include item index parameter..
note 1: since drawing fills each item completely, selected item can't recognized longer. solve issue choosing between more colors: instead of usual systemcolors.hottrack
white text could use other colors like, of course..or bold font..
note 2: since listbox tries 'optimize' not always drawing every item need force adding this:
private void listbox1_selectedindexchanged(object sender, eventargs e) { listbox1.invalidate(); }
Comments
Post a Comment