1

Using a TextBox control, I want to enforce a maximum length. However, the maximum length is based on string size in pixels, not number of characters.

I want to restrict typing more characters if doing so will result in the characters being trimmed by the text renderer, typically being truncated with an ellipsis (...).

The problem is I'm not necessarily using a fixed with font. And I'm using a multiline textbox.

Trevor Elliott
  • 11,292
  • 11
  • 63
  • 102

2 Answers2

1

If your font is not a fixed size, you will have to recalculate the width/height after each character is typed.

Something like this:

public void ValueChanged()
{
    var stringSize = e.Graphics.MeasureString(textBox.Text, textBox.Font);
    if(stringSize.Height > MAXSTRINGHEIGHT)
    {
       textBox.Text = TrimTextAndAddEllipsis(textBox.Text);
    }
}
Carra
  • 17,808
  • 7
  • 62
  • 75
  • The winforms TextBox uses the GDI text renderer, not GDI+, so I would need to use TextRenderer.MeasureText instead of Graphics.MeasureString. Also, I want to emulate textbox "MaxLength" property behavior. The TextBox should not accept any more characters once reaching this point, and give an error beep as it normally does with MaxLength. – Trevor Elliott Oct 23 '12 at 14:45
  • I don't want to trim a string that's too long, I want to avoid the user ever entering a string that's too long based on the rendered size of the text. – Trevor Elliott Oct 23 '12 at 14:46
  • You'll have to combined this answer with chridams comment then. Just replace the maximum character check with a calculation of the width/height check. – Carra Oct 23 '12 at 14:55
  • Your code, even if you changed it to the TextRenderer function, would return the height of a single line instead of the height of multiple lines when the lines are being wrapped in a multiline textbox. – Trevor Elliott Oct 23 '12 at 16:49
  • There's a MeasureString with (text, font, maxWidth). Use that one. – Carra Oct 23 '12 at 21:54
0

I guess you need to set the width for that as per below equation

[border slack] + ([character length] * ([number of characters] + [5 - number of characters Mod 5])). 
Viral Shah
  • 2,263
  • 5
  • 21
  • 36