Link to home
Start Free TrialLog in
Avatar of LorneCash
LorneCashFlag for United States of America

asked on

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.
Avatar of urir10
urir10

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
Avatar of LorneCash

ASKER

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.
Avatar of kaufmed
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

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

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
ASKER CERTIFIED SOLUTION
Avatar of vilgil
vilgil

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>  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!!
you can't set just the width like that you have to set the size as a drawing object