Search code examples
c#.netwinformsuser-controls

Focus control inside an UserControl in a Form


I have a Form let it's name be MyForm and there is a UserControl in the Form, let it's name be MyUserControl. I'd like to set focus to a TextBox that is in MyUserControl.

So the connection looks like this:

- Form ┐
--    UserControl ┐
---            TextBox

When MyForm shown, also MyUserControl is shown and the focus DOES NOT WORK with this solution:

public partial class MyUserControl : UserControl
{

    public MyUserControl()
    {
        InitializeComponent();
    }

    private void MainFormV2HWT_Shown(object sender, EventArgs e)
    {
       ActiveControl = textBox1;
    }
}

BUT IT WORKS WITH THIS SOLUTION:

public partial class MyUserControl : UserControl
{
    // ...

    public TextBox MyTextBox
    {
        get
        {
            return textBox1;
        }
    }

    // ...
}

public class MyForm() : Form
{
    public MyForm()
    {
        InitalizeComponents();
    }


    private void MyForm_Shown(object sender, EventArgs e)
    {
        ActiveControl = myUserControl.MyTextBox;
    }
}

I also tried to set ActiveControl to MyUserControl first, then in MyUserControl set ActiveControl to MyTextBox but it also doesn't work.

Question:

Is my working solution is a nice solution or is there any easier, more nice solution, that's not using MyTextBox from MyForm?


Solution

  • Firstly, You have to focus user control in the form. Something like this:

    public class MyForm() : Form
    {
        private void MyForm_Shown(object sender, EventArgs e)
        {
            myUserControl.Focus();
        }
    }
    

    and then in the user control:

    public partial class MyUserControl : UserControl
    {
        private void MyUserControl _Shown(object sender, EventArgs e)
        {
           textBox1.Select();
        }
    }
    

    This seems the only combination (Focus -> Select) which works.