mawburn
mawburn

Reputation: 2336

WinForms event for TextBox focus?

I want to add an even to the TextBox for when it has focus. I know I could do this with a simple textbox1.Focus and check the bool value... but I don't want to do it that way.

Here is how I would like to do it:

this.tGID.Focus += new System.EventHandler(this.tGID_Focus);

I'm not sure if EventHandler is the correct way to do this, but I do know that this does not work.

Upvotes: 17

Views: 67433

Answers (4)

user3029478
user3029478

Reputation: 196

Here is how you wrap it and declare the handling function, based on Hans' answer.

namespace MyNameSpace
{
 public partial class Form1 : Form
 {
  public Form1()
  {
   InitializeComponent();
  }

  private void Form1_Load(object sender, EventArgs e)
  {
   txtSchedNum.Enter += new EventHandler(txtSchedNum_Enter);
  }
  protected void txtSchedNum_Enter(Object sender, EventArgs e)
  {
   txtSchedNum.Text = "";
  }
 }
}

Upvotes: 2

WEFX
WEFX

Reputation: 8552

I up-voted Hans Passant's comment, but it really should be an answer. I'm working on a Telerik UI in a 3.5 .NET environment, and there is no GotFocus Event on a RadTextBoxControl. I had to use the Enter event.

textBox1.Enter += textBox1_Enter;

Upvotes: 10

Michael J. Gray
Michael J. Gray

Reputation: 9896

this.tGID.GotFocus += OnFocus;
this.tGID.LostFocus += OnDefocus;

private void OnFocus(object sender, EventArgs e)
{
   MessageBox.Show("Got focus.");
}

private void OnDefocus(object sender, EventArgs e)
{
    MessageBox.Show("Lost focus.");
}

This should do what you want and this article describes the different events that are called and in which order. You might see a better event.

Upvotes: 16

lordcheeto
lordcheeto

Reputation: 1091

You're looking for the GotFocus event. There is also a LostFocus event.

textBox1.GotFocus += textBox1_GotFocus;

Upvotes: 23

Related Questions