I need to Align Text for ComboBox by left, right or center. I couldn't find TextAlignment or HorizontalAlignment property for ComboBox in WinForms.
How can i set TextAlignment for ComboBox?
public partial class Form1 : Form
{
ComboBox comboBox;
public Form1()
{
InitializeComponent();
var button = new Button() { Text = "Increase", Size = new Size(100, 20), Location = new Point(10, 10) };
button.Click += button_Click;
this.Controls.Add(button);
comboBox = new ComboBox() { Location = new Point(100, 100), Size = new Size(200, 20), MinimumSize = new Size(0, 0), Font = new Font("Calibri", 11), Text = "Stack Overflow" };
comboBox.Items.Add("One");
comboBox.Items.Add("Two");
comboBox.Items.Add("Three");
comboBox.DrawMode = DrawMode.OwnerDrawVariable;
comboBox.DrawItem += comboBox_DrawItem;
this.Controls.Add(comboBox);
}
void comboBox_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);
}
}
}
}
Above code only sets my combobox item to be displayed in center. How can the text displayed in the combobox be set to center alignment? My goal is to align that text box only not the dropdown items.
Thanks in Advance.
Regards,
Venkatesan R