I am developing a software in winforms, I am stuck in a step where I have
List<KeyValuePair<string, string>>.
and some sample data:
List <KeyValuePair<"S", "1200">>
List <KeyValuePair<"S", "1300">>
List <KeyValuePair<"L", "1400">>
I want to diplay the value of the key pair inside a ListBox, where based in the key of the pair the Item on the ListBox has a diffrent colour, for example if the Key is S, then the Item should be red and if the Key is L the Item should be blue.
Hope you could help me with this.
this is the code I did but it doesn't do what is expected:
e.DrawBackground();
Graphics g = e.Graphics;
Graphics x = e.Graphics;
g.FillRectangle(new SolidBrush(Color.Olive), e.Bounds);
x.FillRectangle(new SolidBrush(Color.Aquamarine), e.Bounds);
foreach (var workOrders in GetItac.FilterWorkOrders())
{
if (workOrders.Key == "S")
{
g.DrawString(workOrders.Value, e.Font, new SolidBrush(e.ForeColor), new PointF(e.Bounds.X, e.Bounds.Y));
}
else
{
x.DrawString(workOrders.Value, e.Font, new SolidBrush(e.ForeColor), new PointF(e.Bounds.X, e.Bounds.Y));
}
}
When you need to show customized results in a
ListBox
control, you need to enable the custom painting of theItems
in the list, setting theListBox
DrawMode property toOwnerDrawVariable
orOwnerDrawFixed
(the latter will set all Items to the same height).(Note → Here, I'm setting it to
OwnerDrawVariable
)The list
Items
painting has to be performed in the DrawItem event of theListBox
, using theDrawItemEventArgs
e.Graphics
object. This allow a correct refresh of theItems
when theListBox
/Form
need repainting.1 - You don't have to multiply your Graphics object.
2 - The
foreach
loop is not needed either, because each Item will be painted when you create/modify theListBox
Items
collection.Note → I'm drawing the
Items
background the way you're showing in your code, but the visual result might be a bit weird (those colors don't blend well).First, simulate the result of your
GetItac.FilterWorkOrders()
method, which will return aList<KeyValuePair<string, string>>
, add those itemsValue
to the list:You can also code it this way, if that method actually returns a
List<KeyValuePair<string, string>>
:When the
ListBox
Items
collection is filled, theDrawItem
event will be raised, to allow the painting of theItems
content.You may need to add the MeasureItem event, to be sure to have a correct measure of each Item's height (mandatory, if you plan on modifying the
ListBox
Font.For each item that is drawn, the text color is chosen testing the
Key
of theKeyValuePair<string, string>
: if its value is"S"
, the text color is set toColor.Red
, the background color toColor.Olive
. Otherwise they're set toColor.Blue
andColor.Aquamarine
.