Search code examples
c#stringtextboxtext-justify

TextBox.Text Doesn't Right Justify


According to my understanding, the code below should right-justify the text if the text is longer than the textbox can show, otherwise it keeps it left-justified.

The problem is that it doesn't actually do this and it's acting really odd. Short strings end up right-justified sometimes and long strings are always left-justified.

What am I doing wrong?

private void textBoxCurrentConfig_TextChanged(object sender, EventArgs e)
{
    SizeF stringSize = new SizeF();
    stringSize = TextRenderer.MeasureText(textBoxCurrentConfig.Text, textBoxCurrentConfig.Font);

    float currentTextWidth = stringSize.Width;
    float allowedTextWidth = textBoxCurrentConfig.Size.Width - 10;

    if (currentTextWidth >= allowedTextWidth) // if the text we want to display is larger than the textbox can hold, right justify it to show the filename
    {
        textBoxCurrentConfig.TextAlign = HorizontalAlignment.Right; // right justify                
    }
    else // otherwise we can display the entire path
    {
        textBoxCurrentConfig.TextAlign = HorizontalAlignment.Left; // left justify
    }

    textBoxCurrentConfig.Refresh();
    this.Refresh();
}

Solution

  • As from your comments, you want to move cursor position according to the text length. You can use TextBox.Select() method for this. Check MSDN for details.

    So if you want to move cursor at the the start of text, you can use

    textBoxCurrentConfig.Select(0, 0);

    and if you want to move cursor at the end of text, you can use

    textBoxCurrentConfig.Select(textBoxCurrentConfig.Text.Length, 0);