在我将“EditOnEnter”设置为true后,如果我没有点击组合框的向下箭头部分,则DataGridViewComboBoxCell
仍然会打开两次。
任何人都有任何线索如何解决这个问题?我有自己的DataGridView
课程,所以我可以通过一些聪明的事件处理程序轻松解决这个问题。
感谢。
答案 0 :(得分:6)
由于您已将DataGridView
的{{1}}属性设置为“EditOnEnter”,因此您可以覆盖其OnEditingControlShowing
方法以确保下拉列表为只要组合框获得焦点,就会显示:
EditMode
每当public class myDataGridView : DataGridView
{
protected override void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e)
{
base.OnEditingControlShowing(e);
if (e.Control is ComboBox) {
SendKeys.Send("{F4}");
}
}
}
控件中的编辑控件获得输入焦点时,上面的代码会检查它是否是一个组合框。如果是这样,它virtually "presses" F4键,导致下拉部分扩展(当任何组合框具有焦点时尝试它!)。这有点像黑客,但它就像一个魅力。
答案 1 :(得分:3)
我使用此解决方案,因为它避免了发送击键:
重写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);
}
答案 2 :(得分:1)
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;
}
}
答案 3 :(得分:0)
答案 4 :(得分:0)
要避免SendKeys问题,请尝试Open dropdown(in a datagrid view) items on a single click中的解决方案。实质上,在OnEditingControlShowing挂钩到组合框的Enter事件时,在Enter事件处理程序中,设置ComboBox.DroppedDown = true。这似乎有同样的效果,但没有@Cody Gray提到的副作用。