Selecting TextBox Text

M

Mike Frank

I am activating an InputPanel automatically, when entering a TextBox. I'm handling GotFocus and
LostFocus events and it works fine.

Now I want additionally to select all the text in the TextBox, when it got the focus, so the user
can start overwriting the existing text. So I added a textBox.SelectAll to the GotFocus handler
(code snippet below), but it does not work. If stepping through with the debugger I can see, that,
the text is selected, but after leaving the method, the selection by the click into the TextBox is
restored.

private void tbCriteria_GotFocus(object sender, EventArgs e)
{
this.inputPanel.Enabled = true;
tbCriteria.SelectAll();
}

I've tried also to make a special TextBox, that overrides it's OnGotFocus method and do the
SelectAll after base.OnGotFocus, but this does show the same effect.

I found no other events on the CF TextBox, that would handle the entering of a TextBox.

My workaround now, is to delete the text. This is right in the typical scenario for my app, but I
have cases, where I want the user to be able to edit the existing text.

Any Ideas?

Mike
 
S

Simon Hart

You need to call the Focus() method after calling SelectAll();

IE:
private void tbCriteria_GotFocus(object sender, EventArgs e)
{
this.inputPanel.Enabled = true;
tbCriteria.SelectAll();
tbCriteria.Focus();
}

Simon.
 
S

Sergey Bogdanov

As Daniel suggested you can workaround it with timer. Here you are
helper class:

public class TextBoxHelper
{
TextBox _tb;
Timer _t = new Timer();

public TextBoxHelper(TextBox tb)
{
_tb = tb;
_t.Tick += new EventHandler(t_Tick);
_t.Interval = 10;
}

public void SelectAll()
{
_t.Enabled = true;
}

private void t_Tick(object sender, EventArgs e)
{
_tb.SelectAll();
_t.Enabled = false;
}
}


and usage:

private void textBox1_GotFocus(object sender, System.EventArgs e)
{
TextBoxHelper tbh = new TextBoxHelper(sender as TextBox);
tbh.SelectAll();
}
 
S

Simon Hart

Sorry....only just relised what I suggested which won't work unless you are
calling it from a forms load event. I have found just called SelectAll()
without the Focus() will not work.

Simon.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top