Search Amazon:

Change the Color of Individual ListBox items in C# .NET

You can set the color of individual items in a ListBox using C# in your .NET WinForm by writting your own handler for the listbox's DrawItem event.

Set the ListBox's DrawMode property:

Add a standard ListBox to your .NET WinForm then set it's DrawMode property to OwnerDrawFixed which forces the ListBox's DrawItem event to be fired.

Write the handler for the DrawItem event:

private void lstBox_DrawItem(object sender, _
          System.Windows.Forms.DrawItemEventArgs e)
    {
    //
    // Draw the background of the ListBox control for each item.
    // Create a new Brush and initialize to a Black colored brush
    // by default.
    //
    e.DrawBackground();
    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(((ListBox)sender).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();
    }

In the InitializeComponent section associate your handler to the DrawItem event:

        this.lstBox.DrawItem += 
                new System.Windows.Forms.DrawItemEventHandler(this.lstBox_DrawItem);

Sign In
  User Id 
  Password 


Submit Your Own Code and Articles




About TheScarms
About TheScarms

Ask me your programming questions

I read every email and answer all I can.

User Feedback: Be the first to add a comment! Items to Show:     

     
You must log in to post feedback.
Comment:    
 

If you use this code, please mention "www.TheScarms.com"

Email this page


TheScarms AppSentinel lets you securely copy protect and create evaluation versions of your software

TheScarms(tm) AppSentinel lets you quickly and easily create evaluation versions of your software and stop unauthorized copying and unregistered use of your programs!

Get your free
trial copy today!


      The World's Number 1 Web Host

© Copyright 2008 TheScarms