C# Highlighted text in WinForms combo box

只谈情不闲聊 提交于 2019-12-06 15:42:16
Jeff Roe

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.

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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!