Rabeea qabaha Rabeea qabaha - 10 months ago 64
Vb.net Question

Combobox items from Right to Left

I have custom 'combobox' and I'm using Arabic language and I need it from Right to Left, In default 'combobox' I can change it from properties but in this custom 'Combobox' its not changed, so how can I modify the class to make it Right to Left?

This is what I'm using:

Class AdvancedComboBox
Inherits ComboBox
Public Shadows Property DrawMode() As System.Windows.Forms.DrawMode
Return m_DrawMode
End Get
m_DrawMode = Value
End Set
End Property
Private Shadows m_DrawMode As System.Windows.Forms.DrawMode
Public Property HighlightColor() As Color
Return m_HighlightColor
End Get
m_HighlightColor = Value
End Set
End Property
Private m_HighlightColor As Color

Public Sub New()
MyBase.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed
Me.HighlightColor = Color.Orange
AddHandler Me.DrawItem, New DrawItemEventHandler(AddressOf AdvancedComboBox_DrawItem)
End Sub

Private Sub AdvancedComboBox_DrawItem(sender As Object, e As DrawItemEventArgs)
If e.Index < 0 Then
End If

Dim combo As ComboBox = TryCast(sender, ComboBox)
If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
e.Graphics.FillRectangle(New SolidBrush(HighlightColor), e.Bounds)
e.Graphics.FillRectangle(New SolidBrush(combo.BackColor), e.Bounds)
End If

e.Graphics.DrawString(combo.Items(e.Index).ToString(), e.Font, New SolidBrush(combo.ForeColor), New Point(e.Bounds.X, e.Bounds.Y))

End Sub
End Class

Answer Source

It's unclear why the the RightToLeft property isn't sticking for you in the properties box, but since you are custom drawing, you should use a right aligned property. Also, best to use TextRenderer instead of DrawString to match the renderer used by other controls:

'e.Graphics.DrawString(combo.Items(e.Index).ToString(), e.Font,
'                      New SolidBrush(combo.ForeColor), New Point(e.Bounds.X, e.Bounds.Y))

TextRenderer.DrawText(e.Graphics, combo.Items(e.Index).ToString, e.Font, e.Bounds,
                      combo.ForeColor, Color.Empty,
                      TextFormatFlags.Right Or TextFormatFlags.VerticalCenter)