Tag Archives: Beautiful Code

Simple, Elegant and Creative – I love this solution

I needed to have all of the text selected when a user clicked on a text box so it would be easy to overwrite the contents without having to hit Ctrl-A. The problem was that I just couldn’t get this code working:

private void myTextbox_Enter(object sender, EventArgs e)

I could call .SelectAll() from anywhere else and it would work fine, but just not from the .Enter event.

It turns out that:

Calling .SelectAll() during the .Enter or .GotFocus events won’t work because if the user clicked the textbox, the caret will be placed where he clicked, thus deselecting all text.

Also, calling .SelectAll() during the .Click event won’t work because the user won’t be able to select any text with the mouse; the .SelectAll() call will keep overwriting the user’s text selection. )

So, how to find a way to call .SelectAll() after the .Enter() event has been handled? My instinct (and many of the solutions I saw) all involved manually tracking the focus state with a boolean flag and either calling .SelectAll() at a later stage depending on the flag or manually redrawing the textbox as needed. All just looked like messy contortions, embarrassing compared to the code I try to write, and most likely flawed.

Then I came across this solution:

private void selectedFolderPath_Enter(object sender, EventArgs e)
    BeginInvoke((Action)(() => selectedFolderPath.SelectAll()));

It seems so blindingly obvious now.  Just call it asynchronously! 

Simple, elegant and creative.