Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I'm writing an FTP program that displays the list of files to be transferred in a listbox. When the file is transferred successfully, I would like to change the background color to green and if it fails, change it to red. I am not seeing how to do this. Anyone know how to change the background color of a single item?

Thank you,
Posted

I wrote an article that customizes the drawing in a ListBox.

Anagrams - A Word Game in C#[^]

The following is an excerpt of the appropriate section of the article:

The Word List

I wanted a way to show the user what he'd typed, so I decided on a list box. As the program validates and accepts submitted words, they are added to the list box (sorted alphabetically). Then, when the user clicked Solve or the round expired naturally, I wanted to show all of the words that were possible, yet show the words that the user had submitted in such a way as to highlight those words.

To accomplish this, I set the list box's DrawMode property to be OwnerDrawFixed, and then overrode the DrawItem behavior. This allowed me to draw certain items with different appearances. I settled on dark gray text for words that were not discovered by the player, and bold red italic text for words the user found.


If you download the code for the article, you'll get a clear idea of what you'll need to do.
 
Share this answer
 
This code colors the item's background based on index - ammend to work on a property of the item at that index.

(Form [FormMain] with a ListBox added called listBox)
C#
using System.Drawing;
using System.Windows.Forms;

namespace CP.QA.WinForms
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
            listBox.DrawMode = DrawMode.OwnerDrawFixed;
            listBox.DrawItem += new DrawItemEventHandler(listBox_DrawItem);
            listBox.Items.AddRange(new object[] { "A", "B", "C" });
        }

        void listBox_DrawItem(object sender, DrawItemEventArgs e)
        {
            if (e.Index > -1)
            {
                if (e.Index == 0)
                    e.Graphics.FillRectangle(Brushes.Green, e.Bounds);
                else if (e.Index == 1)
                    e.Graphics.FillRectangle(Brushes.Red, e.Bounds);
                else
                    e.DrawBackground();
                using (Brush textBrush = new SolidBrush(e.ForeColor))
                {
                    e.Graphics.DrawString(listBox.Items[e.Index].ToString(), e.Font, textBrush, e.Bounds.Location);
                }
            }
        }
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900