0

I have a little problem with a combobox.

I need to put the background color of a combobox in red when there is a value in it.

I'm using the following code :

if (!string.IsNullOrEmpty(ComboTransmis.Text))
    ComboTransmis.BackColor = Color.OrangeRed;
else
    ComboTransmis.BackColor = Color.White;

But the result is this :

enter image description here

There is only text which have the backcolor, I need all element have it and I have no idea how to do it.

If anyone have an idea ?

Thank you in advance

Thomas Rollet
  • 1,573
  • 4
  • 19
  • 33
  • I think if i understand the question correctly you need to write a custom control to do this. P.s. in order to iterate through each combobox on your form you will need to specify all subsequent containers and loop through each of their items. – Master Yoda Oct 12 '17 at 08:55
  • @MasterYoda It's just for this one – Thomas Rollet Oct 12 '17 at 08:57
  • have a look at this question: https://stackoverflow.com/questions/6468024/how-to-change-combobox-backgound-color-not-just-the-drop-down-list-part. You need to modify the combobox yourself to achieve this however you lose the 3d style and gain flat. – Master Yoda Oct 12 '17 at 08:59
  • 1
    @MasterYoda Your last comment help me ! It just need to put the `FlatStyle` propertie to `Flat` and the `BackColor` apply on all element. Thanks for your light ! May the force be with you ! – Thomas Rollet Oct 12 '17 at 09:04

1 Answers1

1

You need to modify the combobox yourself to achieve this however you lose the 3d style and gain flat.

Based on this answer:

Change the combobox DrawMode property to OwnerDrawFixed, and handle the DrawItem event:

private void ComboTransmis_DrawItem(object sender, DrawItemEventArgs e)
{
   int index = e.Index >= 0 ? e.Index : 0;
   var brush = Brushes.Black;
   e.DrawBackground();
   e.Graphics.DrawString(ComboTransmis.Items[index].ToString(), e.Font, brush, e.Bounds, StringFormat.GenericDefault);
   e.DrawFocusRectangle();
}
Master Yoda
  • 4,334
  • 10
  • 43
  • 77
  • p.s. this question might also be useful for you going forward: https://stackoverflow.com/questions/20812275/windows-form-combobox-custom-form-color :) – Master Yoda Oct 12 '17 at 09:16