Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
448 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...