Try to select all text in TextBox when focus/clicked
20:06 11 Jan 2021

I try to imitate the behaviour when the user clicks on a username field (for example) and all the text (name) will be selected automatically to make easier to replace it with a new one. But when the user clicks again on the field the text/name turn unselected state, so the user can continue to write text from the cursor. I'm sure everybody know what I'm trying to describe as we all met this many times when we write in a text field or want to modify it's content...

So the issue is when I use the Enter focus event and apply SelectAll(), just not working at all! The text still not selected. I tried to use Click event too, which worked fine, but I got difficulties with the second click as all mouse click run the SelectAll() method again the text always still selected.. probably I could use global variables which store the selection state of the text and change states vica-versa, but I don't want to use any extra variable if don't necessary (each for all TextBox... nope).

There should be a simple and elegant solution for this as many-many application & website use this behaviour to make the users' life easier. I read a few forum and found some solution but they look unnecessarily more complex than I hoped.

This is the relevant part of my code... nothing special!

    private void G_tbx_canvasSize_Enter(object sender, EventArgs e)
    {
        (sender as TextBox).SelectAll();
    }

This should work on this way:

  • User clicks on the TextBox (TB)
  • TB focused
  • The code run and select all the text
  • User clicks again on TB
  • As this already focused, the code won't run again so text unselect itself by default.. (I tested this!)
  • If user clicks away and click on TB again, everything run again and again..

Please help! I can't figure out why this is occur any issue, it shouldn't be happen...

Thanks in advance!

c# winforms events textbox click