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..?

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.