views:

52

answers:

2

This seems like such a simple thing but I just can't get it to work.

I have a single line text box that has a lot of text. What I want to happen is that whenever the text box receives focus, it scrolls to the end of the text so that it comes into view and the cursor is at the end ready to accept new text.

In the text box's GotFocus event I call textBox.ScrollToEnd(). It looks like all this does is move the cursor to the end of the text box but not actually bring the end into view.

What am I missing?

A: 

This should do the trick:

textbox.SelectionStart = textbox.Text.Length;
textbox.ScrollToCaret();
textbox.Refresh();
Ezweb
This is for Windows Forms, not WPF. And the call to Refresh is unnecessary...
Thomas Levesque
+1  A: 

You should be able to do it using these members:


EDIT: not sure why ScrollToEnd isn't working... Anyway, this code works:

textBox.CaretIndex = txt.Text.Length;
var rect = textBox.GetRectFromCharacterIndex(txt.CaretIndex);
textBox.ScrollToHorizontalOffset(rect.Right);
Thomas Levesque
I tried calling textBox.ScrollToEnd() in GotFocus but it doesn't bring the end of the string into focus. Setting the CaretIndex just moves the caret position but doesn't bring that position into view. So if my text box contains more text than can be fit and I want to scroll to the end whenever it gets focus, how would I do that? All I have in my small sample is a single textBox, Width="80" and in its GotFocus method I tried TextBoxBase.ScrollToEnd, TextBox.CaretIndex, and a combination of the two to scroll to the end of a long string. If you got it to work, can you post a sample?
Flack
@Flack, see my updated answer
Thomas Levesque