textbox.Focus() not working in C#

Dark Knight picture Dark Knight · Jan 4, 2011 · Viewed 50.9k times · Source

am wondering why this code fails to focus the textbox...?

private void sendEmail_btn_Click(object sender, EventArgs e)
{    
    String sendTo = recipientEmail_tbx.Text.Trim();
    if (!IsValidEmailAddress(sendTo))
    {
        MessageBox.Show("Please Enter valid Email address","Cognex" MessageBoxButtons.OK, MessageBoxIcon.Error);                
        recipientEmail_tbx.Focus();
    }
}

Answer

Daniel Peñalba picture Daniel Peñalba · Jan 4, 2011

Use Select() instead:

recipientEmail_tbx.Select();

Focus is a low-level method intended primarily for custom control authors. Instead, application programmers should use the Select method or the ActiveControl property for child controls, or the Activate method for forms.

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx