Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to figure out where to put "..." if text is bigger than container

Let's say I have a Label inside a Panel. The text is going to be bigger than the Panel sometimes, but not always. How would I figure out what part of the text I should at "..." in front of without hard-coding exactly how many characters it would take, because each character isnt the same size.

if (bigLabel.Width >= this.ClientRectangle.Width - 10) {
    dotLabel.Location = new Point(this.ClientRectangle.Width - 10 - dotLabel.Width);
}
else {
    dotLabel.Location = new Point(this.Width + 10, this.Height + 10);
}
like image 994
Oztaco Avatar asked Dec 07 '25 07:12

Oztaco


2 Answers

Leave it up to TextRenderer.DrawText() to figure that out itself. Specify the TextFormatFlags.EndEllipsis option. You'll find a code sample in this answer.

Which is already built in to the Label control. Set its AutoSize property to False and AutoEllipis property to True to have it all done automatically. And you get a tooltip for free that shows the missing text.

like image 199
Hans Passant Avatar answered Dec 08 '25 19:12

Hans Passant


Use Graphics.DrawString method (TextRenderer.DrawText is a GDI way, Graphics.DrawString - GDI+). Set StringFormat.Trimming property to StringTrimming.EllipsisCharacter (EllipsisWord, EllipsisPath).

like image 44
Dennis Avatar answered Dec 08 '25 20:12

Dennis