Dark Knight
Dark Knight

Reputation: 3577

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();
    }
}

Upvotes: 49

Views: 63387

Answers (4)

JGFMK
JGFMK

Reputation: 8884

Use the Form_Activated event handler, in conjunction with a firstActivation boolean.

private bool firstActivation = true;
private Control firstWindowsControl = null;

...

private void DynamicForm_Activated(object sender, EventArgs e)
{
    if (firstActivation)
    {
        firstActivation = false;
        bool fwcPresent = (firstWindowsControl != null);
        Console.WriteLine($"DynamicForm_Activated: firstWindowControl present: {fwcPresent}");
        if (fwcPresent)
        {
            firstWindowsControl.Focus();
        }

    }

Upvotes: 0

Abhishek Maurya
Abhishek Maurya

Reputation: 195

Add Delay some miliSec. Delay then call Focus() and Not forget to put inside Dispatcher.

Task.Delay(100).ContinueWith(_ =>
     {
         Application.Current.Dispatcher.Invoke(new Action(() =>
         {
             TextBoxNAme.Focus();
         }));
     });

Upvotes: 13

Balasubramani M
Balasubramani M

Reputation: 8328

Even I tried with lots of above solutions but none of them worked for me as am trying to focus on page load. Finally I got this solution and it worked.

private void txtBox_LayoutUpdated(object sender, EventArgs e)
{
    txtBox.Focus();
}

Upvotes: 3

Daniel Peñalba
Daniel Peñalba

Reputation: 31847

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

Upvotes: 127

Related Questions