如何在第一次单击时激活组合框 (Datagridview) [英] How to activate combobox on first click (Datagridview)
问题描述
在 winforms 中,您需要单击组合框两次才能正确激活它 - 第一次是聚焦它,第二次是实际获取下拉列表.
In winforms, you need to click the combobox twice to properly activate it - the first time to focus it, the second time to actually get the dropdown list.
如何更改此行为,使其在第一次点击时激活?
How do I change this behavior so that it activates on the very first click?
这是用于 DATAGRIDVIEW 组合框.
This is for DATAGRIDVIEW combobox.
推荐答案
我意识到这是一个老问题,但我想我会将我的解决方案提供给任何可能需要这样做的人.
I realize this is an old question, but I figured I would give my solution to anyone out there that may need to be able to do this.
虽然我找不到任何答案来做到这一点......我确实找到了一个不同的答案对我有帮助的问题.
While I couldn't find any answers to do exactly this... I did find an answer to a different question that helped me.
这是我的解决方案:
private void datagridview_CellEnter(object sender, DataGridViewCellEventArgs e)
{
bool validClick = (e.RowIndex != -1 && e.ColumnIndex != -1); //Make sure the clicked row/column is valid.
var datagridview = sender as DataGridView;
// Check to make sure the cell clicked is the cell containing the combobox
if(datagridview.Columns[e.ColumnIndex] is DataGridViewComboBoxColumn && validClick)
{
datagridview.BeginEdit(true);
((ComboBox)datagridview.EditingControl).DroppedDown = true;
}
}
private void datagridview_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
datagridview.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
以上代码必须绑定到datagridview的CellEnter事件中.
我希望这会有所帮助!
添加了列索引检查以防止在选择整行时崩溃.
edit: Added a column index check to prevent crashing when the entire row is selected.
谢谢,通宵进行上述编辑
edit2:代码现在与 CellEnter 而不是 CellClick 事件相关联.
edit2: Code is now to be tied to the CellEnter rather than the CellClick event.
谢谢,HaraldDutch 对上述编辑
edit3:任何更改都会立即提交,这将使您无需单击另一个单元格来更新当前组合框单元格.
edit3: Any changes will committed immediately, this will save you from clicking in another cell in order to update the current combobox cell.
这篇关于如何在第一次单击时激活组合框 (Datagridview)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!