We help IT Professionals succeed at work.

How can I make a fixed width autosizing label?

I want to make a label that will wrap text and expand down but where I can give it a fixed width... the only way I've come up with to do this so far is to use a txtbox with this code:

    Private Sub Test_ResizeEnd(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.ResizeEnd
        txtPrompt.Height = 13 * System.Math.Truncate(txtPrompt.PreferredSize.Width / txtPrompt.Width) + txtPrompt.PreferredSize.Height
    End Sub

Open in new window



This works 99% but depending on the length of words it rarely will find a combination where the height is calculated wrong.
Comment
Watch Question

Commented:
Put the label inside a div container, some thing like this:

<div style="text-overflow : ellipsis; overflow: hidden; width: 100px; overflow-y: hidden; height:50px">
    <asp:Label Width="100px" Text="Text Here" ID="Label1" runat="server" ></asp:Label>
</div>



http://msdn.microsoft.com/en-us/library/ms534673.aspx

Author

Commented:
thank you for the comment but can you translate that into vb for me I'm not sure how exactly I can use your suggestion.
Most Valuable Expert 2011
Top Expert 2015

Commented:
You could probably get away with:
Private Sub Label1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label1.TextChanged
    Const MAXSIZE As Integer = Integer.MaxValue
    Dim strSize As New Size(Me.Label1.Width, MAXSIZE)

    strSize = Me.Label1.GetPreferredSize(strSize)
    Me.Label1.Height = strSize.Height
End Sub

Open in new window

Most Valuable Expert 2011
Top Expert 2015

Commented:
I probably should have made that more generic  :)
Private Sub Label_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label1.TextChanged
    Const MAXSIZE As Integer = Integer.MaxValue

    Dim lbl As Label = DirectCast(sender, Label)
    Dim strSize As New Size(lbl.Width, MAXSIZE)

    strSize = lbl.GetPreferredSize(strSize)
    lbl.Height = strSize.Height
End Sub

Open in new window

Author

Commented:
I think I'm stick using a textbox as a label cuz I need the label to wrap text and that's just not a property of a label
Commented:
Hi Lornecash

It is simple.
Set the following properties for the label in the properties window :
AutoSize = True
Minimumsize.Width = 100
Maximumsize.Width = 100

'Note :- Here 100 is the preferred fixed for the label. You can set it to anything you want but both minimum and maxium should be same
Most Valuable Expert 2011
Top Expert 2015

Commented:
>>  It is simple.

Indeed. I played around with MaximumSize, but not MinimumSize. I guess that's why it didn't work for me  :(

Good call vilgil   :)

Note: It doesn't seem to like having the border set to FixedSingle. 3D seems to work, though. I could be screwing that up too, though!!

Author

Commented:
you can't set just the width like that you have to set the size as a drawing object