2

I have a path selector in my Visual C# Express 2010 form application.

I do it using a FolderBrowserDialog and a (single line) TextBox, to show the selected path. Using the following line in my UI refresh code.

this.textBoxFolder.Text = this.folderBrowserDialog1.SelectedPath;

The ReadOnly property is set to true and TextAlign property is set to Right using the form designer, because the selected path is often longer than the TextBox, and I prefer to show the right-side of the path. The forms designer generates this:

// 
// textBoxFolder
// 
this.textBoxFolder.Location = new System.Drawing.Point(40, 72);
this.textBoxFolder.Name = "textBoxFolder";
this.textBoxFolder.ReadOnly = true;
this.textBoxFolder.Size = new System.Drawing.Size(160, 20);
this.textBoxFolder.TabIndex = 13;
this.textBoxFolder.TabStop = false;
this.textBoxFolder.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;

Whenever the chosen path is shorter than the textbox size, the Right alignment works. (But this is not really important)

Whenever the chosen path is longer than the textbox size, the Right alignment has no effect, the string in the textbox is displayed such that the left-most character is visible, and right-most are hidden.

I know that in a normal single line TextBox (ReadOnly = false), when an overly-long string is typed in by hand, the right most chars are visible, even when focus goes away, regardless of whether TextAlign is set to Left / Right / Center!

In other words, my goal is, when TextBox.Text is programmatically set (as opposed to typed in), and the string is longer than the width of the TextBox, how do I get the right-most chars to be visible?

Doochz
  • 1,039
  • 2
  • 14
  • 25

2 Answers2

6

Instead of setting the TextAlign property, you should move the caret to the last character:

textBoxFolder.Text = this.folderBrowserDialog1.SelectedPath;
textBoxFolder.SelectionStart = textBox1.Text.Length - 1;

Setting SelectionStart actually moves the caret to the specified position. And that makes the character at that position visible in the TextBox.

If you can use a Label instead of a text box, you can use the one created by Hans Passant here that uses TextFormatFlags.PathEllipses flag while drawing the text.

Community
  • 1
  • 1
Mohammad Dehghan
  • 17,853
  • 3
  • 55
  • 72
  • Thank you! Setting `SelectionStart` did exactly what I wanted! – Doochz Mar 13 '13 at 12:05
  • Note in general if there's a chance of empty strings then you probably want something like textBoxFolder.SelectionStart = Math.Max(0, textBox1.TextLength-1); – Kevin Holt Mar 15 '19 at 15:30
0

Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows CE Platform Note: In Pocket PC-based applications, a single-line text box supports only left alignment. A multiline text box can be aligned on the left, right, or center.