C# Listbox.DrawItem to color each lines

2019-02-21 02:26发布

问题:

I have some code to change how listbox act. I can change the color of text, but I am unable to change the color of the background of each line.

This is in a for loop for every of my lines

LBLines is an array of string store in a global variable

if (LBLines[e.Index] != "None")
{
       e.Graphics.FillRectangle(new SolidBrush(Color.FromName(LBLines[e.Index])),
e.Bounds.X,e.Bounds.Y,e.Bounds.Width,e.Bounds.Height);
}

This will color EVERY lines of the same color, even those listed as "None", thou what I need is that they stay same color as default background color.

EDIT: Comparaison is not the problem, problem come from the e.Graphics.FillRectangle. It seems to color ALL the lines spaces, regardless of the one I am drawing.

EDIT2: Modified code to show that h was equal to e.Index

回答1:

Hard to say without more context around your code (the loop, the method,...), but this code does what I think it is you want:

public partial class Form1 : Form
{
    string[] Colors { get; set; }

    public Form1()
    {
        InitializeComponent();
        Colors = new string[] { "red", "blue", "white", "none", "orange" };
        listBox1.Items.AddRange(Colors);
    }

    private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
    {
        e.DrawBackground();
        if (Colors[e.Index] != "none")
        {
            using (var brush = new SolidBrush(Color.FromName(Colors[e.Index])))
            {
                e.Graphics.FillRectangle(brush, e.Bounds);
            }
        }
        e.Graphics.DrawString(Colors[e.Index], Font, SystemBrushes.ControlText, e.Bounds);
    }
}

Note that the DrawStyle property of the ListBox is set to OwnerDrawFixed.



标签: c# listbox