Tuesday 31 March 2015

Change the ForeColor of individual items in a ComboBox (C# Winforms)


Following steps-

1-  select drowmode property to ownerDrawFixed

2-

private void Form2_Load(object sender, EventArgs e)
        {
         
                this.comboBox1.Items.Add("Test1");
                this.comboBox1.Items.Add("Test2");
                this.comboBox1.Items.Add("Test3");
                this.comboBox1.Items.Add("Test4");
                this.comboBox1.Items.Add("Test5");
                this.comboBox1.Items.Add("Test6");
           
        }

        private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            // 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 (IsItemDisabled(e.Index))// compare  date with your list. 
            {
                brush = Brushes.Red;
            }
            else
            {
                brush = Brushes.Gray;
            }

            // Draw the text   
            e.Graphics.DrawString(text, ((Control)sender).Font, brush, e.Bounds.X, e.Bounds.Y);
        }

        void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (IsItemDisabled(comboBox1.SelectedIndex))
                comboBox1.SelectedIndex = -1;
        }

        bool IsItemDisabled(int index)
        {
            // We are disabling item based on Index, you can have your logic here
            return index % 2 == 1;
        }


No comments:

Post a Comment

Excel Sort values in ascending order using function TEXTJOIN

 Excel ::  Text ::  1,3,5,2,9,5,11 Result :: 1,2,3,5,5,9,11 Formula ::     TEXTJOIN ( ",",1,SORT(MID(SUBSTITUTE( A1 ,","...