C# Listbox.DrawItem to color each lines

眉间皱痕 提交于 2019-12-01 14:43:42

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!