How to set focus on a control within a custom control?
Asked Answered
P

2

6

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?

Pict answered 5/2, 2015 at 7:15 Comment(1)
Thanks, Brother! ('Me Too', just because I often see those together, however have now idea what it means)Exemplary
P
1

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();
}
Pict answered 22/5, 2015 at 8:43 Comment(0)
F
1

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");
Fluorinate answered 5/2, 2015 at 7:26 Comment(5)
@Ivan-MarkDebono, What kind of control you are trying to focus ? and from which control ?Fluorinate
A simple textbox within a custom control. The custom control is used as an editing control for an ObjectListView.Pict
also, is your custom user control being focused ? you can check this with Focused Property.- userControl11.FocusedFluorinate
No. It returns false.Pict
that is the reason for it to be not happening. This happens because your customusercontrol is a repository editor for a ObjectListBox.Fluorinate
P
1

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();
}
Pict answered 22/5, 2015 at 8:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.