ListBox inserts items into color

I use ListBox to insert text like You add Michael in your database , You delete Michael , ...

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

It is working fine. How can I set the color once black (for insertion) and once red (for removal)? 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 when pasting:

  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 some elements, scrolling does not work correctly - the text does not appear. What am I doing wrong? Or is this another way to do this?

+4
source share
3 answers

You should use:

 e.Bounds.Top 

instead:

 e.Index * listBox1.ItemHeight 

In addition, before you draw text, I recommend that you draw a background so that you can see which item is selected if the list supports selection or supports the color of the list of the desired item in any case:

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

And you must get rid of the brush you create in order to draw the text.

+5
source

Do you consider using ListView in report view instead of list? Then you do not need to adjust the drawing to get the colors.

+6
source

Change the pattern to

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

Source: https://habr.com/ru/post/1402627/


All Articles