Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right justified combobox in C#

By default the items in the C# Combobox are left aligned. Are there any options available to change this justification apart from overriding DrawItem method and setting the combobox drawmode --> DrawMode.OwnerDrawFixed?

Cheers

like image 239
this-Me Avatar asked Jun 23 '10 05:06

this-Me


People also ask

How do you center a ComboBox?

Simply select your combo box, click the "Align" button, and then choose how you want your text to be aligned (left, center, right, etc.).

What is ComboBox in C sharp?

A ComboBox displays a text box combined with a ListBox, which enables the user to select items from the list or enter a new value. The DropDownStyle property specifies whether the list is always displayed or whether the list is displayed in a drop-down.


2 Answers

You could just set the control style to RightToLeft = RightToLeft.Yes if you don't mind the drop widget on the other side as well.

or

set DrawMode = OwnerDrawFixed; and hook the DrawItem event, then something like

    private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
    {
        if (e.Index == -1)
            return;
        ComboBox combo = ((ComboBox) sender);
        using (SolidBrush brush = new SolidBrush(e.ForeColor))
        {
            e.DrawBackground();
            e.Graphics.DrawString(combo.Items[e.Index].ToString(), e.Font, brush, e.Bounds, new StringFormat(StringFormatFlags.DirectionRightToLeft));
            e.DrawFocusRectangle();
        }
    }
like image 55
Paul Avatar answered Oct 11 '22 20:10

Paul


In WPF this would be as easy as specifying an ItemContainerStyle. In Windows Forms it's a little trickier. Without custom drawing, you could set the RightToLeft property on the ComboBox but this would unfortunately also affect the drop down button.

Since Windows Forms uses a native ComboBox, and Windows doesn't have a ComboBox style like ES_RIGHT that affects the text alignment, I think your only option is to resort to owner draw. It would probably be a good idea to derive a class from ComboBox and add a TextAlignment property or something. Then you would only apply your drawing if TextAlignment was centered or right aligned.

like image 37
Josh Avatar answered Oct 11 '22 20:10

Josh