How to right-justify the text in a combobox?

  • Thread starter Thread starter amnonevo
  • Start date Start date
A

amnonevo

A text box on a VB.NET form has a TextAlign property. A combo box does
not. How to align text in a combo box to the right?
 
Hi,

You will to draw it yourself.


Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
For x As Integer = 0 To 20
ComboBox1.Items.Add(x.ToString)
Next
ComboBox1.DrawMode = DrawMode.OwnerDrawFixed
ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList
End Sub

Private Sub ComboBox1_DrawItem(ByVal sender As Object, ByVal e As
System.Windows.Forms.DrawItemEventArgs) Handles ComboBox1.DrawItem
Dim g As Graphics = e.Graphics
Dim s As String
Dim d As Date
Dim dr As DataRowView
Dim dt As Date
Dim br As Brush = SystemBrushes.WindowText
Dim brBack As Brush
Dim rDraw As Rectangle
Dim bSelected As Boolean = CBool(e.State And DrawItemState.Selected)
Dim bValue As Boolean = CBool(e.State And
DrawItemState.ComboBoxEdit)

rDraw = e.Bounds
rDraw.Inflate(-1, -1)

If bSelected And Not bValue Then
brBack = Brushes.LightBlue
g.FillRectangle(Brushes.LightBlue, rDraw)
g.DrawRectangle(Pens.Blue, rDraw)
Else
brBack = Brushes.White
g.FillRectangle(brBack, e.Bounds)
End If

br = Nothing
brBack = Nothing
rDraw = Nothing

Try
s = ComboBox1.Items.Item(e.Index).ToString
Catch
s = ""
End Try

Dim x, y As Integer

Dim sf As New StringFormat
Dim rf As RectangleF = RectangleF.op_Implicit(e.Bounds)
sf.Alignment = StringAlignment.Far

g.DrawString(s, ComboBox1.Font, Brushes.Black, rf, sf)
End Sub

Ken
 
Ken,

Thanks a lot for the post. I just hope that there is a simpler way to
right align text in a combo box.

Amnon
 
Back
Top