Question

My question is basically, does implementing DrawItem for my ComboBox in WinForms, change my Text property, why and I can I stop it?

Because my OwnerDraw event works perfectly except the Text property "also" gets set to the same logic as all the items in Items[] (ie implemented in DrawItem event below)

For context, I show URL's in the list, but some are so long I basically chop them and put the text "..." at the end - to make it more readable. I have DataSource set so that it renders one property of my class "DisplayUrl" but uses another "Url" for the actual value. (MyUrl below)

At the end of some code, I explicitly set cmbUrl.Text = "THE FULL TEXT"

But somehow the DrawItem event is also effecting the "Text" property because even after running this code, once the DrawItem event is finished my Text property is set to the same as Item[0]. ie With the text chopped off - as in "THE FULL T..."

void cmbUrl_DrawItem(object sender, DrawItemEventArgs e)
{              
  var text = ((MyUrl)((ComboBox)sender).Items[e.Index]).DisplayUrl;
  var brush = text.Contains("bla) ? Brushes.DarkGreen : Brushes.Black;

  // Fill in the background
  e.Graphics.FillRectangle(new SolidBrush(e.BackColor), e.Bounds);
  if (e.Index < 0) return;
  // Work out where every thing goes
  int nX = e.Bounds.Left;
  int nY = e.Bounds.Top;
  const int nMarg = 2;
  int nH = e.Bounds.Height - (2 * nMarg);

  // Draw the Colour Gymph
  var penFore = new Pen(e.ForeColor);
  var rectGymph = new Rectangle(nX + nMarg, nY + nMarg, nH, nH);
  e.Graphics.FillRectangle(brush, rectGymph);
  e.Graphics.DrawRectangle(penFore, rectGymph);

  var fullWidth = nX + nH + (2 * nMarg);
  e.Graphics.DrawString(text, e.Font, brush, fullWidth, e.Bounds.Top);
}
Was it helpful?

Solution

I think you want to show your the full Text in your combobox and just want to show the short text in Items drop-down list, so the solution may be this:

private void cmbUrl_DropDown(object sender, EventArgs e){
    cmbUrl.DisplayMember = "DisplayUrl";
}
private void cmbUrl_DropDownClosed(object sender, EventArgs e){
    cmbUrl.DisplayMember = "Url";        
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top