ListBox insert items in color

落爺英雄遲暮 提交于 2020-01-03 17:29:51

问题


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?


回答1:


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.




回答2:


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:


Change the drawing to

 e.Graphics.DrawString(item.Message, 
   listBox1.Font, 
   new SolidBrush(item.ItemColor), 
   0,
   e.Bounds.Top);


来源:https://stackoverflow.com/questions/9803064/listbox-insert-items-in-color

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