Selecting TextBox Text#

There was a question in the newsgroups about selecting text in a textbox when it receives focus.  I thought it was as simple as TextBox.SelectAll() but apparently it's not!  If you trap the OnFocus event and use SelectAll() it does work but when the OnFocus handler is done the base Textbox puts the carret where ever the user clicked the stylus thus removing the selectAll(). 

Here is some code to overcome this:

private TextBox currentTB = null;
private void GenericTextBox_GotFocus(object sender, System.EventArgs e)
{
  this.currentTB = (TextBox)sender;
  System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(SelectAll));
  t.Start();
}   
 
private void SelectAll()
{
  if(this.currentTB!=null)
  {
    //Usuall the Invoke should finish after the got focus event finishs. If you experience problems add a sleep
    //System.Threading.Thread.Sleep(50);
    currentTB.Invoke(new EventHandler(InvokeSelectAll));
    currentTB = null;
  }
}

private void InvokeSelectAll(object sender, System.EventArgs e)
{
  ((TextBox)sender).SelectAll();
}


Friday, March 11, 2005 2:02:15 PM (Eastern Standard Time, UTC-05:00) #    Comments [2]  |  Tracked by:
"Selecting Control Text" (Mark Arteaga) [Trackback]

 

All content © 2008, Mark Arteaga
On this page
Related Sites
Archives
Sitemap
Disclaimer

Powered by: newtelligence dasBlog 1.9.7174.0

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Send mail to the author(s) E-mail

Theme design by Jelle Druyts