Quantcast
Channel: Windows Forms General forum
Viewing all articles
Browse latest Browse all 12583

ComboBox and TextAlign

$
0
0

I was looking for a way to right align the text in a combobox and I came across this post:

http://social.msdn.microsoft.com/forums/en-US/vbgeneral/thread/e5d22714-7d11-468b-b119-953be31bcc0c/

So I made the following class which uses the same principle and lets you select the alignment:

publicclass TextAlignedComboBox : ComboBox
{
  [Category("Behaviour"), DefaultValue(DrawMode.OwnerDrawFixed),
    Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]publicnew DrawMode DrawMode
  {get { returnbase.DrawMode; }privateset { base.DrawMode = value; }
  }

  [Category("Appearance"), DefaultValue(ComboBoxStyle.DropDownList),
    Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]publicnew ComboBoxStyle DropDownStyle
  {get { returnbase.DropDownStyle; }privateset { base.DropDownStyle = value; }
  }

  [Category("Appearance"), DefaultValue(HorizontalAlignment.Left)]public HorizontalAlignment TextAlign { get; set; }public TextAlignedComboBox()
  {this.DrawMode = DrawMode.OwnerDrawFixed;this.DropDownStyle = ComboBoxStyle.DropDownList;this.TextAlign = HorizontalAlignment.Left;
  }protectedoverridevoid OnDrawItem(DrawItemEventArgs e)
  {// Draw background
    e.DrawBackground();// Get textstring text = string.Empty;if (e.Index >= 0)
      text = this.Items[e.Index].ToString();// Get alignment
    TextFormatFlags textFormatFlags;switch (this.TextAlign)
    {case HorizontalAlignment.Center:
        textFormatFlags = TextFormatFlags.HorizontalCenter;break;case HorizontalAlignment.Left:
        textFormatFlags = TextFormatFlags.Left;break;case HorizontalAlignment.Right:
        textFormatFlags = TextFormatFlags.Right;break;default:thrownew Exception("Bad TextAlign value.");
    }// Draw text
    TextRenderer.DrawText(e.Graphics, text, e.Font, e.Bounds, e.ForeColor, textFormatFlags);// Draw focus rectangle
    e.DrawFocusRectangle();
  }
}

The alignment works and it acts like a DropDownList (can't change the values) but it doesn't look like a DropDownList. In the following picture, the top left and right sections are my custom combobox, the bottom left section is what it should look like.


Viewing all articles
Browse latest Browse all 12583

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>