Align Text in Combobox

user1366440 picture user1366440 · Aug 5, 2012 · Viewed 63.8k times · Source

I want to align my text in combo box so that it will show in the center of combobox tell me how to do this also you can see there is a default border around a combo box when it is in focus how can i remove that border also Kindly solve my two problems Thanks

Answer

Martin Braun picture Martin Braun · Feb 6, 2014

This article will help you: http://blog.michaelgillson.org/2010/05/18/left-right-center-where-do-you-align/

The trick is to set the DrawMode-Property of the ComboBox to OwnerDrawFixed as well as subscribe to its event DrawItem.

Your event should contain the following code:

// Allow Combo Box to center aligned
private void cbxDesign_DrawItem(object sender, DrawItemEventArgs e)
{
  // By using Sender, one method could handle multiple ComboBoxes
  ComboBox cbx = sender as ComboBox;
  if (cbx != null)
  {
    // Always draw the background
    e.DrawBackground();

    // Drawing one of the items?
    if (e.Index >= 0)
    {
      // Set the string alignment.  Choices are Center, Near and Far
      StringFormat sf = new StringFormat();
      sf.LineAlignment = StringAlignment.Center;
      sf.Alignment = StringAlignment.Center;

      // Set the Brush to ComboBox ForeColor to maintain any ComboBox color settings
      // Assumes Brush is solid
      Brush brush = new SolidBrush(cbx.ForeColor);

      // If drawing highlighted selection, change brush
      if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
        brush = SystemBrushes.HighlightText;

      // Draw the string
      e.Graphics.DrawString(cbx.Items[e.Index].ToString(), cbx.Font, brush, e.Bounds, sf);
    }
  }
}

ComboBox-Preview

To right align the items you can simply replace StringAlignment.Center with StringAlignment.Far.