hlominac
asked on
Find the length of a word in a list box or a rich text box
I have a list of words I wish to display vertically both in a list box and in a rich text box (RTB). The RTB is fully docked on a panel. I wish to determine the width of the panel to accommodate all the words. What is the best way to do this in VB.NET? It needs to depend upon the font size of the word.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
On your form, place a label. Set Visible = False and AutoSize = True. Then set the font and size to be the same as the listbox's.
Then you can iterate through the items in the list box and place each string as the text of the label. The label will autosize to fit the entire string. Measure the width of the label, and compare it to the longest one you've found so far. By the time you finish iterating through the list box items, you will have found the longest one. Then just set the width of the list box to match.
For example:
Dim str As String
Dim len As Integer
Dim savelen As Integer = 0
For Each str In ListBox1.Items
Label1.Text = str
Label1.Refresh()
len = Label1.Width
If len > savelen Then savelen = len
Next
ListBox1.Width = savelen