4
votes

Is there anyway to stop the selected item in a winforms combo box from being automatically highlighted when it is set? (either via the combobox property SelectedIndex or SelectedItem).

What happens is that we populate a combo box with a set of items and then set the index for the item we want to show in the combo but this then causes the text to be highlighted. When the combobox is disabled this means that it is very hard to read the text because the highlight colour is blue and the text colour is white. Looks like this behaviour is by design but it is very annoying!

The only solution I've found online and tried which works is to subclass the combobox control but this is too invasive and would mean that we would have to replace all combo boxes in our application to solve this issue. I've also tried setting the SelectionLength property on the combo to 0 after the parent control has loaded and have also tried calling Select(0,0) on the combobox but neither has the desired effect.

Any ideas?

Thanks

3
Similar question here: stackoverflow.com/questions/786119/…CJBS

3 Answers

3
votes

This appears to be a bug in the native Windows implementation of ComboBox with DropDownStyle of DropDown.

I think the best solution is to handle the ComboBox's Resize event, setting the SelectionLength property to 0 (zero). That solution is detailed in answers to this question:

Editbox portion of ComboBox gets selected automatically

However, I found that even that hackish fix to work around this bug does not always work. If the ComboBox is in a TableLayoutPanel, and if that TableLayoutPanel has more than one column with a Percent Size Type, then that fix often does not work.

A picture is worth a thousand words. See the following screen shot of a form I made to demonstrate the problem.

enter image description here

0
votes

this will work

private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
   // Draw the background.
   e.DrawBackground();
  // Determine the forecolor based on whether or not
  // the item is selected.
  Brush brush;
  // Get the item text.
  string text = ((ComboBox)sender).Items[e.Index].ToString();
  if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
  {
    brush = Brushes.White;
  }
     // Draw the text.
    e.Graphics.DrawString(text, ((Control)sender).Font, brush, e.Bounds.X, e.Bounds.Y);
}
0
votes

Highlight text from zero index to the last index:

comboBox1.Select(0, comboBox1.Text.Length);

Highlight text from particular index to the last index (it's useful for search text when entering a characters within the combobox):

comboBox1.Select(text.Length, comboBox1.Text.Length);