Wolf
Wolf

Reputation: 880

How to force a focus on a control in windows forms

I am trying to focus a "search" textbox control in my windows forms application. This textbox is inside a user control, which is inside a panel which is inside a windows form (if it is important). I tried 3 methods which I could find:

// 1
this.ActiveControl = myTextBox;

// 2
myTextBox.Focus();

// 3
myTextBox.Select();

Neither of them seems to work. I mean for example when I try the first one, active control is really set to myTextBox, but when I try to write something on keyboard, textbox doesn't accept it and I have to first click inside the textbox to get focus. This is same with all of the methods. Am I missing something?

Upvotes: 17

Views: 41069

Answers (2)

Anonymous Helper
Anonymous Helper

Reputation: 29

You could do these logic steps to set your control to be the focus:

your_control.Select();
your_control.Focus();

Enjoy! :)

Upvotes: 1

Wolf
Wolf

Reputation: 880

Ok, finally found the answer:

As I said my textbox is inside user control which is inside panel which is inside a form. When I need my user control I add it to panel. To get focus on my textbox I have to firstly focus my user control so something like this: In my top Form:

panel.Controls.Add(myUserControl);
myUserControl.Focus();

and then in my user control:

myTextBox.Select();

Note that if I used: myTextBox.Focus() it wouldn't work (don't know why). Also if I used myUserControl.Select() instead of myUserControl.Focus() it wouldn't work either.

This seems to be the only combination which works.

Upvotes: 26

Related Questions