tags:

views:

42

answers:

1

Hello, 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  A: 

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.

Tor Livar
Yeah, I removed loop but it didnt fix the thing.
Wildhorn
You may also want to do e.DrawBackground() when the string is "None"...
Tor Livar
No, it seems background does it for ALL the lines. That's weird because DrawString work just fine.
Wildhorn
This is what I have as code (except for var names) and it doesnt work.
Wildhorn
Ok, I made ONE change. The only difference between your code and mine was that I set all the bounds one by one, while you, you just used e.bounds. I changed that and now it works... wtf?
Wildhorn
Strange - mine works even if I change it to explicitly describing the rectangle like you did (as I would expect) - but I'm glad you got it to work now :-)
Tor Livar