Link to home
Start Free TrialLog in
Avatar of ArunVashist
ArunVashistFlag for India

asked on

visual C#, maskedTextbox, moving cursor to begining on focus

Hi Friends,

I am developing windows application using VS .net 3.5 using C#, right now in my application i have used Maskedtextboxes. Now i want to know how can i move my cursor to beginning of MaskedTextbox on focus.

Moreover as I want to do the same thing for all maskedtextboxes how can i do it with single function wired with on focus or any other Event .

I have already tried  <controlname>.SelectionStart = 0, but its not working.


Thanks,
Avatar of RyanAndres
RyanAndres
Flag of United States of America image

use Select method.
Select(int start, int length)

ie.
maskedTextBox1.Select(0,0);
ASKER CERTIFIED SOLUTION
Avatar of wht1986
wht1986
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 ArunVashist

ASKER

Thanks wht1986,

it works..  it would be kind if you just explain me why we need to do it this way... actually i could'nt understand the second line of function.

thanks in advance.
The masked textbox actually is doing its own select on focus because of the mask, so when we say move to the beginning, the built in select says move to the end executes after ours.

So what we need to do is basically queue up (delay the execution of our select) by using the BeginInvoke method.
I only know this because I had to solve the same thing this week at work and it took me countless google hours to find the answer, but I'm glad I could help
Hi,

What you could do is the attached.
If you want to make it reusable then create a generic event with the same signature as that of events you require fired and wire the other events up within this at runtime ie mosedown, enter etc.
namespace Scratchpad
{
    public partial class Form1 : Form
    {
        private bool f = false;
 
        public Form1()
        {
            InitializeComponent();
        }
 
        void maskedTextBox1_GotFocus(object sender, EventArgs e)
        {
            maskedTextBox1.SelectionStart = 0;
        }
 
        private void maskedTextBox1_MouseClick(object sender, MouseEventArgs e)
        {
            if (this.f)
            { this.maskedTextBox1.SelectionStart = 0; }
            this.f = false;
        }
 
        private void maskedTextBox1_Enter(object sender, EventArgs e)
        {
            this.f = true;
            this.maskedTextBox1.SelectionStart = 0;
        }
 
        private void maskedTextBox1_MouseMove(object sender, MouseEventArgs e)
        {
            this.f = false;
        }
    }
}

Open in new window