I have a form with a ComboBox. I found the post: http://blog.michaelgillson.org/2010/05/18/left-right-center-where-do-you-align/ that helped me to centre-align all the items in the DropDown list. The problem is that the selected item (the item shown in the comboBox.Text property) remains left aligned.
How can I centre-align also the selected Item?
The code is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ComboBoxTextProperty
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
List<string> source = new List<string>() { "15", "63", "238", "1284", "13561" };
comboBox1.DataSource = source;
comboBox1.DrawMode = DrawMode.OwnerDrawFixed;
comboBox1.DropDownStyle = ComboBoxStyle.DropDown;
comboBox1.SelectedIndex = 0;
comboBox1.DrawItem += new DrawItemEventHandler(ComboBox_DrawItem);
}
/// <summary>
/// Allow the text in the ComboBox to be center aligned.
/// Change the DrawMode Property from Normal to either OwnerDrawFixed or OwnerDrawVariable.
/// If DrawMode is not changed, the DrawItem event will NOT fire and the DrawItem event handler will not execute.
/// For a DropDownStyle of DropDown, the selected item remains left aligned but the expanded dropped down list is centered.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBox_DrawItem(object sender, DrawItemEventArgs e)
{
ComboBox comboBox1 = sender as ComboBox; // By using sender, one method could handle multiple ComboBoxes.
if (comboBox1 != null)
{
e.DrawBackground(); // Always draw the background.
if (e.Index >= 0) // If there are items to be drawn.
{
StringFormat format = new StringFormat(); // Set the string alignment. Choices are Center, Near and Far.
format.LineAlignment = StringAlignment.Center;
format.Alignment = StringAlignment.Center;
// Set the Brush to ComboBox ForeColor to maintain any ComboBox color settings.
// Assumes Brush is solid.
Brush brush = new SolidBrush(comboBox1.ForeColor);
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) // If drawing highlighted selection, change brush.
{
brush = SystemBrushes.HighlightText;
}
e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(), comboBox1.Font, brush, e.Bounds, format); // Draw the string.
}
}
}
}
}
ComboBox
control and override bothOnPaint
andOnDrawItem
. – user10216583