在我将“EditOnEnter”设置为 true 后,DataGridViewComboBoxCell
如果我不单击组合框的向下箭头部分,仍然需要单击两次才能打开。
任何人都知道如何解决这个问题?我有自己DataGridView
使用的类,所以我可以通过一些我希望的智能事件处理程序轻松地在系统范围内解决这个问题。
谢谢。
在我将“EditOnEnter”设置为 true 后,DataGridViewComboBoxCell
如果我不单击组合框的向下箭头部分,仍然需要单击两次才能打开。
任何人都知道如何解决这个问题?我有自己DataGridView
使用的类,所以我可以通过一些我希望的智能事件处理程序轻松地在系统范围内解决这个问题。
谢谢。
由于您已经将DataGridView
'EditMode
属性设置为“EditOnEnter”,因此您可以重写其OnEditingControlShowing
方法以确保下拉列表在组合框获得焦点时立即显示:
public class myDataGridView : DataGridView
{
protected override void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e)
{
base.OnEditingControlShowing(e);
if (e.Control is ComboBox) {
SendKeys.Send("{F4}");
}
}
}
每当控件中的编辑控件DataGridView
获得输入焦点时,上面的代码都会检查它是否是组合框。如果是这样,它实际上“按下”了 F4 键,这会导致下拉部分展开(当任何组合框具有焦点时尝试它!)。这有点像黑客,但它就像一个魅力。
我使用了这个解决方案,因为它避免了发送击键:
覆盖 OnCellClick 方法(如果您是子类)或订阅 CellClick 事件(如果您是从另一个对象更改 DGV 而不是作为子类)。
protected override void OnCellClick(DataGridViewCellEventArgs e)
{
// Normally the user would need to click a combo box cell once to
// activate it and then again to drop the list down--this is annoying for
// our purposes so let the user activate the drop-down with a single click.
if (e.ColumnIndex == this.Columns["YourDropDownColumnName"].Index
&& e.RowIndex >= 0
&& e.RowIndex <= this.Rows.Count)
{
this.CurrentCell = this[e.ColumnIndex, e.RowIndex];
this.BeginEdit(false);
ComboBox comboBox = this.EditingControl as ComboBox;
if (comboBox != null)
{
comboBox.DroppedDown = true;
}
}
base.OnCellContentClick(e);
}
protected override void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e)
{
base.OnEditingControlShowing(e);
DataGridViewComboBoxEditingControl dataGridViewComboBoxEditingControl = e.Control as DataGridViewComboBoxEditingControl;
if (dataGridViewComboBoxEditingControl != null)
{
dataGridViewComboBoxEditingControl.GotFocus += this.DataGridViewComboBoxEditingControl_GotFocus;
dataGridViewComboBoxEditingControl.Disposed += this.DataGridViewComboBoxEditingControl_Disposed;
}
}
private void DataGridViewComboBoxEditingControl_GotFocus(object sender, EventArgs e)
{
ComboBox comboBox = sender as ComboBox;
if (comboBox != null)
{
if (!comboBox.DroppedDown)
{
comboBox.DroppedDown = true;
}
}
}
private void DataGridViewComboBoxEditingControl_Disposed(object sender, EventArgs e)
{
Control control = sender as Control;
if (control != null)
{
control.GotFocus -= this.DataGridViewComboBoxEditingControl_GotFocus;
control.Disposed -= this.DataGridViewComboBoxEditingControl_Disposed;
}
}
为避免 SendKeys 问题,请尝试单击打开下拉列表(在数据网格视图中)项目中的解决方案。本质上,在组合框的 Enter 事件的 OnEditingControlShowing 挂钩中,在 Enter 事件处理程序中,设置 ComboBox.DroppedDown = true。这似乎具有相同的效果,但没有@Cody Gray 提到的副作用。