0

Hi,

I would like to know how to get the width of a textstring and/or how to substring a string to a given width (not length), if possible. The reason is that i use a multicolumn listbox and should know how to cut of the length of the strings so they dont exceeds the columns-width.

The most ideel will be to cut a textstring in a given width (not length). Any surgestions how to do this..?

2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by sniper1983
0

Try this:
It is a listbox with a button.

Public Class Form1
    Dim str As String = "abcdefghijklmnopqrstuvwxyz"

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ListBox1.Items.Add(TrimToSize("abcdefghijklmnopqrstuvwxyz"))
        ListBox1.Items.Add(TrimToSize("This is a major line"))
        ListBox1.Items.Add(TrimToSize("Thomas, is that you?"))
        ListBox1.Items.Add(TrimToSize("It's alive!"))
    End Sub

    Private Function TrimToSize(ByVal Str As String) As String
        Dim wid As Integer = ListBox1.ClientSize.Width
        Dim g As Graphics = ListBox1.CreateGraphics
        Dim siz As New SizeF
        Do
            siz = g.MeasureString(Str, ListBox1.Font)
            If siz.Width > wid Then Str = Str.Substring(0, Str.Length - 1)
        Loop While siz.Width > wid
        g.Dispose()
        Return Str
    End Function

End Class
0

Thanks, I'll try this later and get back to you.. The idea seems great.. :)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.