Wednesday, July 6, 2011

How to right justify text in textbox

WinForm TextBox control does not have any property or method that right justify text in the control. But this goal can be archieved by using SelectionStart and SelectionLength property. If you set SelectionStart to last position of the textbox and give a SelectionLength to zero, it mimics moving TextBox position to the end.

Here is how to right-justify text in the TextBox control.

private void RightJustify(TextBox textbox)
  textbox.SelectionStart = textbox.Text.Length;
  textbox.SelectionLength = 0;