ListBox insert items in color

2019-06-25 06:21发布

I use ListBox for inserting text like You add Michael in your database, You delete Michael, ...

 listBox1.Items.Insert(0,"You add " + name + " in your database\n");

It works ok. How can i set color once black (for insert) and once red (for deletion)? I tried with this:

 public class MyListBoxItem
    {
        public MyListBoxItem(Color c, string m)
        {
            ItemColor = c;
            Message = m;
        }
        public Color ItemColor { get; set; }
        public string Message { get; set; }
    }

    private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
    {
        MyListBoxItem item = listBox1.Items[e.Index] as MyListBoxItem; // Get the current item and cast it to MyListBoxItem

        if (item != null)
        {
            e.Graphics.DrawString( // Draw the appropriate text in the ListBox
            item.Message, // The message linked to the item
            listBox1.Font, // Take the font from the listbox
            new SolidBrush(item.ItemColor), // Set the color 
            0, // X pixel coordinate
            e.Index * listBox1.ItemHeight // Y pixel coordinate.  Multiply the index by the ItemHeight defined in the listbox.
            );
        }
        else
        {
            // The item isn't a MyListBoxItem, do something about it
        }
    }

And on insertion:

 listBox1.Items.Insert(0, new MyListBoxItem(Color.Black, "You add " + name + " in your database\n"));
 listBox1.Items.Insert(0, new MyListBoxItem(Color.Red, "You delete " + name + "\n"));

This code works, but when i insert multiple items, scrol doesn't work correctly - text does not appear. What am i doing wrong? Or is any other way to do this?

3条回答
姐就是有狂的资本
2楼-- · 2019-06-25 06:41

Have you considered using a ListView in report view instead of a listbox? Then you don't have to customize the drawing in order to get colors.

查看更多
等我变得足够好
3楼-- · 2019-06-25 06:43

You should use:

e.Bounds.Top

instead of:

e.Index * listBox1.ItemHeight

Also, before drawing the text, I recommend drawing the background so you can see which item is selected, if the list supports selection, or support the list's desired item background color in any case:

using (Brush fill = new SolidBrush(e.BackColor))
{
   e.Graphics.FillRectangle(fill, e.Bounds);
}

And you should properly dispose of the Brush that you're creating to draw the text.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-06-25 06:52

Change the drawing to

 e.Graphics.DrawString(item.Message, 
   listBox1.Font, 
   new SolidBrush(item.ItemColor), 
   0,
   e.Bounds.Top);
查看更多
登录 后发表回答