Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16320

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?

Upvotes: 6

Views: 2688

Answers (2)

Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16320

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

Upvotes: 1

Rohit Prakash
Rohit Prakash

Reputation: 1972

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");

Upvotes: 1

Related Questions