Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListBox insert items in color

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?

like image 544
JanOlMajti Avatar asked Dec 10 '22 01:12

JanOlMajti


1 Answers

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.

like image 110
BlueMonkMN Avatar answered Dec 11 '22 15:12

BlueMonkMN