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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With