我有一个Form,它包含一个名为gridParameters的DataGridView控件。 我基于某些值在其上添加控件,以添加不可用的控件(例如,DateTimePicker):
DateTimePicker dtp = new DateTimePicker();
gridParameters.Controls.Add(dtp);
dtp.Location = rowCellLocation;
dtp.Size = rowCellSize;
dtp.CustomFormat = "yyyy/MM/dd";
dtp.Format = DateTimePickerFormat.Custom;
dtp.Tag = rowId;
dtp.ValueChanged += dtp_SelectedValueChanged;
dtp.Visible = true;
该代码位于循环中,迭代网格行,并且位于If语句中(我为某些行添加DateTimePicker,为其他行添加NumericUpDown,基于行单元格值)。变量rowCellLocation,rowCellSize和rowId在每一行的循环中设置。
我的DataGridView选择模式是一个完整的行选择。 当我切换到行时,我想让添加的控件(DateTimePicker,NumericUpDown ...)获得焦点,例如,当我用鼠标单击一行时。
为此,我尝试了以下方法: 在创建控件的循环中,我将控件设置为相关的行Tag属性。 在网格Row_Enter事件中(我也尝试了CurrentCellChanged),我添加了以下代码:
if (gridParameters.CurrentRow.Tag != null)
{
((Control)gridParameters.CurrentRow.Tag).Focus();
}
我也尝试过使用Select()和
this.ActiveControl = (Control)gridParameters.CurrentRow.Tag;
上述所有内容都没有集中在控件上。
我放置一个断点,代码到达这一行,Tag属性包含需要聚焦的控件,并执行它,但我无法让控件聚焦。
更新:将焦点设置到DataGridView的另一个控件外部,可以正常工作(例如,将焦点设置为“确定”按钮工作)。