Search code examples
c#.netwinformslistbox

change color item listbox c#


I have created a ListBox to which I add elements during code compilation. and I want to record its color when adding one element (so that each added element has a different color)

listBox1.Items.Add(string.Format("Місце {0} | В роботі з {1} | ({2} хв)", temp[7].Substring(6, 4), temp[8].Substring(11, 5), rezult));   `

I tried everywhere possible to embed this change

BackColor = Color.Yellow;ForeColor = Color.Yellow;

I am working with listbox because I have seen so many answers about ListView.


Solution

  • Set the listbox DrawMode to either OwnerDrawFixed or OwnerDrawVariable and set this as the DrawItem event handler:

    private void listBox1_DrawItem(object sender, DrawItemEventArgs e){
        if(e.Index == 1) e.DrawBackground(); //use e.Index to see if we want to highlight the item
        else e.Graphics.FillRectangle(new SolidBrush(Color.Yellow), e.Bounds); //This does the same thing as e.DrawBackground but with a custom color
        e.DrawFocusRectangle();
        if(e.Index < 0) return;
        TextRenderer.DrawText(e.Graphics, (string)listBox1.Items[e.Index], listBox1.Font, e.Bounds, listBox1.ForeColor, TextFormatFlags.Left);
    }