user261710
user261710

Reputation: 39

How to Color particular item of combobox

I want to color all "Unselectable" Text from combo box. How can i do this? I tried it but i am unable to do this.

My Code is Given Below:

private class ComboBoxItem
{
    public int Value { get; set; }
    public string Text { get; set; }
    public bool Selectable { get; set; }
}

private void Form1_Load(object sender, EventArgs e)
{
    this.comboBox1.ValueMember = "Value";
    this.comboBox1.DisplayMember = "Text";
    this.comboBox1.Items.AddRange(new[] {
        new ComboBoxItem() { Selectable = true, Text="Selectable0", Value=0,  },
        new ComboBoxItem() { Selectable = true, Text="Selectable1", Value=1},
        new ComboBoxItem() { Selectable = true, Text="Selectable2", Value=2},
        new ComboBoxItem() { Selectable = false, Text="Unselectable", Value=3},
        new ComboBoxItem() { Selectable = true, Text="Selectable3", Value=4},
        new ComboBoxItem() { Selectable = false, Text="Unselectable", Value=5},
    });

    this.comboBox1.SelectedIndexChanged += (cbSender, cbe) =>
    {
        var cb = cbSender as ComboBox;

        if (cb.SelectedItem != null && cb.SelectedItem is ComboBoxItem && ((ComboBoxItem)cb.SelectedItem).Selectable == false)
        {
            // deselect item
            cb.SelectedIndex = -1;
        }
    };
}

I am working in C#.NET.

Upvotes: 1

Views: 3637

Answers (2)

TaW
TaW

Reputation: 54433

You need to set the ComboBox.DrawMode to OwnerDrawxxx and script the DrawItem event e.g. like this:

 private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
 {

    e.DrawBackground();
     // skip without valid index
    if (e.Index >= 0) 
    {
      ComboBoxItem cbi = (ComboBoxItem)comboBox1.Items[e.Index];
      Graphics g = e.Graphics;
      Brush brush =  new SolidBrush(e.BackColor);
      Brush tBrush = new SolidBrush(cbi.Text == "Unselectable" ? Color.Red : e.ForeColor);

      g.FillRectangle(brush, e.Bounds);
      e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), e.Font,
                 tBrush, e.Bounds, StringFormat.GenericDefault);
      brush.Dispose();
      tBrush.Dispose();
    }
    e.DrawFocusRectangle();

 }

This part cbi.Text == "Unselectable" is not good, obviously. Since you already have a Property Selectable it should really read !cbi.Selectable" . Of course you must make sure that the property is in synch with the text.

Upvotes: 2

Richard
Richard

Reputation: 180

You need to set the foreground property on the ComboBoxItem to the colour you require.

new ComboBoxItem() { Selectable = false, Text="Unselectable", Value=3, Foreground = Brushes.Red},

MSDN page

Upvotes: -1

Related Questions