Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

textbox.Focus() not working in C#

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();     } } 
like image 537
Dark Knight Avatar asked Jan 04 '11 13:01

Dark Knight


People also ask

How to set focus in TextBox c#?

When showing a form that contains a TextBox, it's common courtesy to focus the TextBox so that the user can begin typing immediately. To focus a TextBox when a Windows Form first loads, simply set the TabIndex for the TextBox to zero (or the lowest TabIndex for any Control on the Form).

Which of the following method of text box can set focus in TextBox control?

Use the SetFocus method when you want a particular field or control to have the focus so that all user input is directed to this object.

What is Focus C#?

The Focus method attempts to give the specified element keyboard focus. The returned element is the element that has keyboard focus, which might be a different element than requested if either the old or new focus object block the request.


1 Answers

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

like image 184
Daniel Peñalba Avatar answered Oct 05 '22 18:10

Daniel Peñalba