K
Keld Laursen
Hi, all.
I am trying to extend a TextBox to select the text in it upon focusing it.
I thought that it could be accomplished by simply attaching a GotFocus event
handler, and then fiddle with SelectionStart and SelectionLength.
I of course found out that this didn't work because the click event fires
afterwards. The suggestion I found on the net were to use a timer, but I
don't like timers for stuff like that.
I therefore tried implementing this little class:
public class SmartTextBox : TextBox
{
private bool m_newFocused;
public SmartTextBox():base()
{
m_newFocused=false;
this.Click += new EventHandler(SmartTextBox_Click);
this.GotFocus +=new System.EventHandler(SmartTextBox_GotFocus);
}
private void SmartTextBox_GotFocus(object sender, System.EventArgs e)
{
this.m_newFocused=true;
}
private void SmartTextBox_Click(object sender, EventArgs e)
{
if(this.m_newFocused)
{
this.m_newFocused=false;
this.SelectionStart=0;
this.SelectionLength=9999;
}
}
}
The code should raise a flag on GotFocus and then act on it when the Click
event fires.
Unfortunately the above code only works for the GotFocus event, but not for
the Click event.
I tried the same kind of code elsewhere, just creating the TextBox and
attaching the events. Here everything works as intended.
Did I do something wrong in creating this?
TIA
Best regards,
Keld Laursen
I am trying to extend a TextBox to select the text in it upon focusing it.
I thought that it could be accomplished by simply attaching a GotFocus event
handler, and then fiddle with SelectionStart and SelectionLength.
I of course found out that this didn't work because the click event fires
afterwards. The suggestion I found on the net were to use a timer, but I
don't like timers for stuff like that.
I therefore tried implementing this little class:
public class SmartTextBox : TextBox
{
private bool m_newFocused;
public SmartTextBox():base()
{
m_newFocused=false;
this.Click += new EventHandler(SmartTextBox_Click);
this.GotFocus +=new System.EventHandler(SmartTextBox_GotFocus);
}
private void SmartTextBox_GotFocus(object sender, System.EventArgs e)
{
this.m_newFocused=true;
}
private void SmartTextBox_Click(object sender, EventArgs e)
{
if(this.m_newFocused)
{
this.m_newFocused=false;
this.SelectionStart=0;
this.SelectionLength=9999;
}
}
}
The code should raise a flag on GotFocus and then act on it when the Click
event fires.
Unfortunately the above code only works for the GotFocus event, but not for
the Click event.
I tried the same kind of code elsewhere, just creating the TextBox and
attaching the events. Here everything works as intended.
Did I do something wrong in creating this?
TIA
Best regards,
Keld Laursen