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
- Create a new Windows Form Application in .NET 4.0 in Visual Studio 2010.
- Add a
TextBox
,MaskedTextBox
, andButton
to the default form - Change the
Mask
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.
- Select the other TextBox. Try clicking on MaskedTextBox. Output shows that
GotFocus
event was called, but text doesn't get selected. - Try clicking on button in form. 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.