How to adjust focus on a control in a user control?

I have a custom control containing a text box and a button. I am using a custom control as an edit control for a specific column in an ObjectListView.

In the CellEditStarting event, I:

private void datalistViewProducts_CellEditStarting(object sender, CellEditEventArgs e) { var ctl = (MyCustomControl)e.Control; e.Control = ctl; } 

The ObjectListView ConfigureControl method already calls the Select control method. It works fine if I have a usercontrol inheriting directly from the standard TextBox.

So, I added the following code to my usercontrol:

 public new void Select() { textBox.Select(); } 

However, having user control as described above, the Select method does not move focus to the text field.

What am I missing here?

+5
source share
2 answers

The only way he finally worked was to add the following code to usercontrol:

 protected override void OnEnter(EventArgs e) { base.OnEnter(e); textBox.Select(); } 
+1
source

You can create a method in CustomUserControl, say FocusControl(string controlName) and then call this method to focus the control in user control.

Create a method in a user control -

 public void FocusControl(string controlName) { var controls = this.Controls.Find(controlName, true); if (controls != null && controls.Count() == 1) { controls.First().Focus(); } } 

Call this method -

 //textBox1 is the name of your focussing control in Custom User Control userControl11.FocusControl("textBox1"); 
+1
source

Source: https://habr.com/ru/post/1212682/


All Articles