4

I have a windows multiline TextBox and is readonly. Can I check if the text within it has reached the the end? My purpose is to enable scroll if text is greater than the TextBox capacity.

Jonathan Nixon
  • 4,940
  • 5
  • 39
  • 53
Nitish
  • 13,845
  • 28
  • 135
  • 263
  • Doesn't the textbox has an `auto` option at the vertical scrollbar property? – Stefan May 21 '14 at 12:08
  • Not to my knowledge. I am using System.Windows.Forms.TextBox – Nitish May 21 '14 at 12:09
  • 1
    Maybe this will help: http://stackoverflow.com/questions/73110/how-can-i-show-scrollbars-on-a-system-windows-forms-textbox-only-when-the-text-d – Stefan May 21 '14 at 12:13

2 Answers2

8

Try this to check if string width is less than the textbox width:

if(TextRenderer.MeasureText(txtBox.Text, txtBoxFont).Width < txtBox.Width)
mrida
  • 1,157
  • 1
  • 10
  • 16
1

The simple, don't-waste-your-time solution is to just set the vertical scrollbar to be visible all the time. If it is not necessary, it won't do anything. But it also won't hurt anything to be visible. This is what basically all text editors, word processors, and countless other applications do.

If you insist on calculating whether a scrollbar is necessary, you can do it, but it'll take quite a bit of work. You'll use the TextRenderer.MeasureText method to determine the size, in pixels, of the text that the control is displaying. Be sure to use the overload that allows you pass in the font, size, text format flags that correspond to the properties of your TextBox control.
(Note that you do not want to use the Graphics.MeasureString method; it uses GDI+, while the TextBox control uses GDI internally, so the results will be inaccurate.)

You'll insert the code in a handler for the TextChanged event so that it will re-calculate the required size each time the contents of the TextBox are updated.

Oh, and once you get the code written and start testing it, you'll notice a strange bug. It'll take you a while to identify it, but I'll save you the trouble: you will have forgotten to account for the width of the scroll bar itself! When the scroll bar is hidden, slightly more text will fit in the control's client area. Fix this by allowing for the width of the scroll bar, which you can determine by querying the SystemInformation.VerticalScrollBarWidth property.

You might also start receiving complaints from your testers that the app has become sluggish. That stands to reason—you are recalculating each time the text in the TextBox changes. There might be some minor optimizations that you can make to your code, but this solution just isn't going to be terribly efficient.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574