I want to select all the contents of a MaskedTextBox
when the clicks (or tabs onto) the control, so they can easily replace the old content. I tried calling SelectAll()
in the Enter
event, but that didn't work at all.
I switched to using the GotFocus
event, which works great when tabbing through controls, but doesn't work when I click on it with the mouse. I would only want to select all the contents when first entering/focusing on the control (subsequent clicks might be used to position the cursor to edit the existing text).
I added a button and tried calling SelectAll()
in the button click event, but that didn't do anything either. What's going on? Is this a bug?
How can I get around this?
Steps to reproduce
TextBox
, MaskedTextBox
, and Button
to the default formMask
property on the MaskedTextBox to "_____". Add some event handlers:
private void maskedTextBox1_GotFocus(object sender, EventArgs e)
{
Debug.WriteLine("GotFocus");
maskedTextBox1.SelectAll();
}
private void button1_Click(object sender, EventArgs e)
{
Debug.WriteLine("Click");
maskedTextBox1.SelectAll();
}
Run the program, entered some data into the MaskedTextBox, tab through controls back to it. It selects the contents of the MaskedTextBox.
GotFocus
event was called, but text doesn't get selected.Tested in Visual Studio 2010 with .NET 4.0 in a Windows Forms Application project
Why this isn't a duplicate of TextBox.SelectAll() does not work with TAB
If you notice, the title says "SelectAll doesn't work with TAB". In my case, it does work with Tab, it doesn't work with the mouse - completely opposite scenario. The answer for that question is to use the GotFocus
event. I'm already using the GotFocus
event, but it doesn't work. That answer does not answer this question. It is clearly not a duplicate. If I'm wrong, please explain in the comments.
Your SelectAll()
is being overwritten by the default functionality of the masked textbox select. I would use the Enter
event, it allows for tabbed entry or mouse click entry to the masked text box. You will most likely need to use the BeginInvoke
method. Try the code below. It worked for me when I tried...
private void maskedTextBox1_Enter(object sender, EventArgs e)
{
BeginInvoke((Action) delegate { SetMaskedTextBoxSelectAll((MaskedTextBox) sender); });
}
private void SetMaskedTextBoxSelectAll(MaskedTextBox txtbox)
{
txtbox.SelectAll();
}
Executing Focus before Select All worked for me:
private void Masked_Enter(object sender, EventArgs e) {
((MaskedTextBox)sender).Focus();
((MaskedTextBox)sender).SelectAll();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With