[英]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. 我使用自定义控件作为ObjectListView中特定列的编辑控件。
On CellEditStarting event I do: 在CellEditStarting事件上我做:
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. ObjectListView的ConfigureControl
方法已经调用了控件的Select
方法。 It works fine if I have a usercontrol inheriting directly from a standard TextBox. 如果我有一个直接从标准TextBox继承的usercontrol,它工作正常。
So I added the following code to my usercontrol: 所以我将以下代码添加到我的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. 但是,如上所述具有用户控件, Select
方法不会将焦点移动到文本框。
What am I missing here? 我在这里错过了什么?
You can create a method in CustomUserControl, say FocusControl(string controlName)
and then call this method to focus the control in Custom Control. 您可以在CustomUserControl中创建一个方法,比如FocusControl(string controlName)
,然后调用此方法将控件聚焦在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");
The only way that made it finally work was to add the following code in the usercontrol: 使它最终工作的唯一方法是在usercontrol中添加以下代码:
protected override void OnEnter(EventArgs e)
{
base.OnEnter(e);
textBox.Select();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.