Introduction
If you have a TextBox
that is too narrow to display all its text, it will show the end of the text on startup:
If you resize it to a width that could display the whole string, the TextBox
will not reposition the text to show all text:
This code will reset the text position to show all text, while maintaining any text selection and carat position.
Background
The .NET TextBox
control is merely a wrapper for the old Win32 edit box control. This limits its functionality, and makes it difficult to customize. Even simple tasks like resizing the height of the TextBox require you to use complex workarounds to accomplish.
When you resize a TextBox
where some of the text is off the left edge of the control, it never repositions the text to show as much as the control will handle. To overcome this limitation, we need to modify the TextBox
text selection.
Using the code
To reset the visible text in the TextBox
, we need to change the carat (cursor) position to the beginning of the string, then back to the end. However, doing this will lose any selection that the user might have made prior to the resize. This routine will determine what is selected in the control, reset the carat location, then restore the user's selection.
Visual Basic:
Private Sub SetAllTextVisible(ByRef tbTextBox As TextBox)
Dim iSelectStart As Integer
Dim iSelectLength As Integer
iSelectStart = tbTextBox.SelectionStart
iSelectLength = tbTextBox.SelectionLength
tbTextBox.Select(0, 0)
tbTextBox.SelectionStart = 0
tbTextBox.Select(iSelectStart, iSelectLength)
End Sub
C#:
public void SetAllTextVisible(TextBox tbTextBox)
{
int startselect;
int selectlength;
startselect = tbTextBox.SelectionStart;
selectlength = tbTextBox.SelectionLength;
tbTextBox.Select(0, 0);
tbTextBox.SelectionStart = 0;
tbTextBox.Select(startselect, selectlength);
}
User Control
Alternatively, you could create a new UserControl
class and change the inheritance on the class declaration from UserControl
to TextBox
. Override the OnSizeChanged
event to call the SetAllTextVisible
routine.
Important: If you change a class inheritence from UserControl
to TextBox
, you will need to open the UserControll.Designer
code and remove the Autoscale
property:
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
public partial class ShowAllTextBox : TextBox
{
public ShowAllTextBox()
{
InitializeComponent();
}
protected override void OnSizeChanged(EventArgs e)
{
SetAllTextVisible();
base.OnSizeChanged(e);
}
public void SetAllTextVisible()
{
int startselect;
int selectlength;
startselect = this.SelectionStart;
selectlength = this.SelectionLength;
this.Select(0, 0);
this.SelectionStart = 0;
this.Select(startselect, selectlength);
}
}
Enjoy!