align text in a ListBox

  • Thread starter Thread starter Tom McL.
  • Start date Start date
T

Tom McL.

I would like to align text in a ListBox to achieve columns.

In the past I could determine the text width in Twips and

pad in required number of blank spaces. But now I'm using

VB2005 and it does not support Twips. How do I accomplish this?



Thanks
 
Hi,

Set the listbox draw mode to ownerdrawnfixed to control how the
text is aligned. This example will use a stringformat to center the text


Public Class Form1

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

End Sub

Private Sub ListBox1_DrawItem(ByVal sender As Object, ByVal e As
System.Windows.Forms.DrawItemEventArgs) Handles ListBox1.DrawItem
Dim g As Graphics = e.Graphics
Dim br As SolidBrush
Dim s As String
Dim sf As New StringFormat

sf.Alignment = StringAlignment.Center

Try
s = ListBox1.Items.Item(e.Index).ToString
Catch ex As Exception
s = ""
Trace.WriteLine(ex.ToString)
End Try

br = New SolidBrush(Color.White)

g.FillRectangle(br, e.Bounds)

If CBool(e.State And DrawItemState.Selected) Then
g.FillRectangle(Brushes.LightBlue, e.Bounds)
End If

g.DrawString(s, ListBox1.Font, Brushes.Black, _
RectangleF.op_Implicit(e.Bounds), sf)

br.Dispose()
End Sub
End Class

Ken
 
Thanks Ken, That procedure worked great.

Now I have tried it using a comboBox it also
worked except when an item is selected the
new format is lost. Is there a way to draw this
into the Editable portion of the ComboBox.

Tom
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top