tags:

views:

49

answers:

2

Hello

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

+1  A: 

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.

Josh Einstein
Hi ... In this case how do i apply the TextAlignment to the control?Are you hinting at the string format here ?
this-Me
No I'm saying you would need to create a control that derives from ComboBox and add a *new* property called TextAlignment. Then in your OnDrawItem method you can take this property into account, rather than hard coding an alignment.
Josh Einstein
Example: http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.drawitem.aspx
Josh Einstein
A: 

You could just set the control style to RightToList = True if you dond mind the drop widget on the other side as well.

or

set DrawMode = OwnerDrawFixed; 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();
        }
    }
Paul
Hi ...There is no difference i can see even after i implemented this handler.
this-Me
not sure why, did you remember to set the property of the combo box DrawMode to OwnerDrawFixed. And do you have some items in the list.
Paul