Link to home
Start Free TrialLog in
Avatar of allelopath
allelopath

asked on

Set cursor position in TextBox

I have a MaskedTextBox with mask "\\ABC0000000".
When the TextBox is displayed, the cursor is at the A. I would like it to be before the first 0.
How do I set the cursor position?
SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of allelopath
allelopath

ASKER

I did this:
this.myTextBox.SelectionLength = 0;
this.myTextBox.SelectionStart = 3;

Open in new window

but it seems to have no effect.
Try focusing the TextBox before you fiddle with the selection points:


this.myTextBox.Focus();
this.myTextBox.SelectionLength = 0;
this.myTextBox.SelectionStart = 3;

Open in new window

If that doesn't help, where and when you do have that code?
No difference using Focus().

I'm playing with the location of those lines of code. The class is a subclass of UserControl. The first location was the constructor. Now I've moved it to OnLoad(), but still no joy.
It's not something that can be done once, such as the Contructor() or OnLoad().  You'd have to do it in the GotFocus() event of your TextBox, for example...
I see your point. In that case, I would like to do something like this:
this.myTextBox.OnGotFocus += new System.EventHandler(this.myTextBox_OnGotFocus);

Open in new window

but OnGotFocus is not an option.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That's it:
private void myTextBox_GotFocus(object sender, EventArgs e)
{
        this.txtCrrNumber.SelectionStart = 3;
        this.txtCrrNumber.SelectionLength = 0;
}

Open in new window