Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hey Guys , tnx for Helping me.
I have a listbox , that shows me logs of my application but some of these logs
are Errors So I Wanna when add an Error to my Listbox , Color of that Item (only that Item) changed to another color like Red.....

I use Forecolor Property befor that but its change colors of all items ..
Posted
Comments
ZurdoDev 5-Dec-14 12:30pm    
I could be wrong but I don't think the .Net control can do separate colors for each item. You'd have to find a 3rd party control.

1 solution

Assuming this is the Windows Forms ListBox control[^], you need to set the DrawMode[^] to OwnerDrawFixed and handle the DrawItem event[^]. MSDN has an example:

private ListBox ListBox1 = new ListBox();

private void InitializeListBox()
{
    ListBox1.Items.AddRange(new Object[] 
        { "Red Item", "Orange Item", "Purple Item" });
    ListBox1.Location = new System.Drawing.Point(81, 69);
    ListBox1.Size = new System.Drawing.Size(120, 95);
    ListBox1.DrawMode = DrawMode.OwnerDrawFixed;
    ListBox1.DrawItem += new DrawItemEventHandler(ListBox1_DrawItem);
    Controls.Add(ListBox1);
}

private void ListBox1_DrawItem(object sender, 
    System.Windows.Forms.DrawItemEventArgs e)
{
    // Draw the background of the ListBox control for each item.
    e.DrawBackground();
    // Define the default color of the brush as black.
    Brush myBrush = Brushes.Black;

    // Determine the color of the brush to draw each item based  
    // on the index of the item to draw. 
    switch (e.Index)
    {
        case 0:
            myBrush = Brushes.Red;
            break;
        case 1:
            myBrush = Brushes.Orange;
            break;
        case 2:
            myBrush = Brushes.Purple;
            break;
    }

    // Draw the current item text based on the current Font  
    // and the custom brush settings.
    e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(), 
        e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
    // If the ListBox has focus, draw a focus rectangle around the selected item.
    e.DrawFocusRectangle();
}
 
Share this answer
 
Comments
Ali-,-reza 5-Dec-14 13:11pm    
tnx for telling me about Drawmode Property, I made it.
BillWoodruff 5-Dec-14 20:14pm    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900