Organizational Research By

Surprising Reserch Topic

How to select the contents of a textbox once it is activated?


I have this simple Userform, where I only have TextBox1 and TextBox2. I enter some text in both of them. Assume the focus is on (the cursor is in) the TextBox2. When I click on TextBox1, I want the whole text in this control to be highlighted (selected). Thus I use this code:

Private Sub TextBox1_Enter()
    With TextBox1
        .SetFocus
        .SelStart = 0
        .SelLength = Len(.Text)
    End With
    MsgBox "enter event was fired"
End Sub
There is a MsgBox at the end which is loaded, that means the event works. However, the text is not highlighted. How to fix this?

I use the Enter event and don't want to use the MouseDown event, because I need the code to also work when the TextBox1 is activated programatically, so I feel the Enter event to be the best choice, as it's fired in both cases! Another drawback of the MouseDown event is: when I click for the second time on the TextBox1, I would not expect the whole text to be highlighted anymore, because the focus was set on the first click and it was not changed after I clicked on the same control for the second time; so in this case I would like the cursor to act normally (not to keep the text marked).

Update
When I click once on the TextBox1, I expect to have this result: enter image description here
If clicked again, the highlight would be removed and the cursor would be placed in the place where it was clicked.
asked May 16, 2015 in Csharpenet by rajesh
0 votes
10 views



Related Hot Questions



Government Jobs Opening


...