Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set focus on a control within a custom control?

I have a custom control containing a textbox and a button. I use the custom control as an editing control for a specific column in an ObjectListView.

On CellEditStarting event I do:

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

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

So I added the following code to my usercontrol:

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

However, having a usercontrol as described above, the Select method does not move the focus to the textbox.

What am I missing here?

like image 272
Ivan-Mark Debono Avatar asked Feb 05 '15 07:02

Ivan-Mark Debono


2 Answers

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

Create the method in your custom 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");
like image 182
Rohit Prakash Avatar answered Oct 19 '22 22:10

Rohit Prakash


The only way that made it finally work was to add the following code in the usercontrol:

protected override void OnEnter(EventArgs e)
{
    base.OnEnter(e);
    textBox.Select();
}
like image 29
Ivan-Mark Debono Avatar answered Oct 20 '22 00:10

Ivan-Mark Debono