Click here to Skip to main content
15,919,434 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a drop-down list(in Windows Forms using C#) whose items appear in different colours according to some conditions. I am unable to retain the colour of a selected item.


C#
public Form1()
     {
         InitializeComponent();

         // cmb.SelectedIndex = 0;



         cmb.Items.Add("1");
         cmb.Items.Add("2");
         cmb.Items.Add("3");
         cmb.Items.Add("4");
         cmb.Items.Add("5");
         cmb.Items.Add("6");

         cmb.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;


     }


          private void cmb_Draw(object sender, DrawItemEventArgs e)
     {
         cmb.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;


         // Draw the background
         e.DrawBackground();

         // Get the item text
         string text = ((ComboBox)sender).Items[e.Index].ToString();

         // Determine the forecolor based on whether or not the item is selected
         Brush brush;

         if (int.Parse( text) > 3 )  // condition check
         {
             brush = Brushes.Red;
         }
         else
         {
             brush = Brushes.Blue;
         }

         // Draw the text
         e.Graphics.DrawString(text, ((Control)sender).Font, brush, e.Bounds.X, e.Bounds.Y);
Posted
Updated 11-Dec-12 23:24pm
v3
Comments
OriginalGriff 12-Dec-12 3:43am    
This is not a good question - we cannot work out from that little what you are trying to do.
Remember that we can't see your screen, access your HDD, or read your mind.
Use the "Improve question" widget to edit your question and provide better information.
[no name] 12-Dec-12 4:00am    
elaborate it... provide your code... then only we can help you... :)
ansh13 12-Dec-12 5:15am    
Code added, plz have a look

1 solution

You can use a variable at the form level scope and call it something like "LastColor" and set the value for it in the "IF" statement when you determine the forecolor, and then when the dropdown list selection changes you can recall the color from the static variable.
 
Share this answer
 

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