3

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);
}
CD Smith
  • 6,597
  • 7
  • 40
  • 66
Oztaco
  • 3,399
  • 11
  • 45
  • 84
  • I tried putting a second label on top of it near the end of the label that has "..." and i would check how big the text is and only show it if the other label is a certain number of pixels big, but that makes it look cut off too. like there would be half of a "B" and a dot on top of it, and i tried counting the characters and splitting it but that sometimes doesn't use up all of the space – Oztaco May 28 '12 at 18:12
  • Please post the code you have and we can take a look at your problem more accurately – CD Smith May 28 '12 at 18:13
  • By the way, kudos to you for learning programming at such a young age, I wish I had! – CD Smith May 28 '12 at 18:15
  • Looks like Hans has the solution for you there. Like he says, just let the `TextRender` figure that out for you on its own :-) – CD Smith May 28 '12 at 18:19

3 Answers3

8

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.

Community
  • 1
  • 1
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • as a follow up question, is it possible to replace the 3 dots with something else, like a dash, or just 2 dots using this method? – Oztaco May 28 '12 at 18:39
  • 1
    No, the ellipsis is a dedicated Unicode glyph, codepoint U+2026. It means only one thing, dashes and dots are Morse code that mean something else :) – Hans Passant May 28 '12 at 18:47
1

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

Dennis
  • 37,026
  • 10
  • 82
  • 150
0

If you use Telerik control - RadLabel, Only set this properties:

this.lblReferralTracking.TextAlignment = System.Drawing.ContentAlignment.MiddleLeft;
this.lblReferralTracking.TextWrap = false;
this.lblReferralTracking.UseCompatibleTextRendering = true;
Stack Overflow
  • 2,416
  • 6
  • 23
  • 45