# Monday, February 07, 2011
« Tip of the Day: Convert XmlDocument to X... | Main | Tip of the Day: Testing emails by saving... »
I recently had a project where the user wanted to color various options in a combobox based on certain values. There were two challenges to it. First, changing the colors. Second, when the combobox is selected, the background color changes to blue by default, which made some of the fonts hard to read. So I set the background color to white by default, so all the fonts could be easily read. Here's the code:

        private void cboDtl_DrawItem(object sender, DrawItemEventArgs e)
        {
            try
            {
 
                e.DrawBackground();
                Brush codeBrush = Brushes.Black;
                string campaignName = String.Empty;
                int currentCampaignIndex = e.Index;
                ArrayList al = (ArrayList)cboDtlCampaign.DataSource;
 
                if ((al != null) && currentCampaignIndex >= 0)
                {
                     if (someCondition)
                         codeBrush = Brushes.Red;
                     else
                         codeBrush = Brushes.Green;

                }
                //Make the background color white so the colors stand out
                e.Graphics.DrawRectangle(new Pen(Color.White), e.Bounds);
                e.Graphics.FillRectangle(Brushes.White, e.Bounds);
 
                e.Graphics.DrawString(campaignName, e.Font, codeBrush, e.Bounds, StringFormat.GenericDefault);
 
                e.DrawFocusRectangle();
 
            }
            catch 
            {
                //just ignore it?
            }
        }

Comments are closed.