DataGridView编辑模式下空单元格显下拉框及值获取异常问题
DataGridView ComboBox列问题修复方案
1. 清空单元格时自动展开下拉框
你之前的代码判断的是CurrentCell.Value,但编辑模式下这个值是编辑前的旧数据,不会实时跟着输入内容更新,所以删到空也触发不了下拉。改成直接读取ComboBox的实时文本就行:
修改ComboBox_KeyPress事件:
void ComboBox_KeyPress(object sender, KeyPressEventArgs e) { var comboBox = sender as ComboBox; if (comboBox == null) return; // 退格键触发后检查文本是否为空 if (e.KeyChar == '\b' && string.IsNullOrWhiteSpace(comboBox.Text.Trim())) { comboBox.DroppedDown = true; } else if (!string.IsNullOrWhiteSpace(comboBox.Text.Trim())) { comboBox.DroppedDown = false; } }
另外,Delete键不会触发KeyPress,所以要加个KeyDown事件处理:
private void ComboBox_KeyDown(object sender, KeyEventArgs e) { var comboBox = sender as ComboBox; if (comboBox == null) return; if (e.KeyCode == Keys.Delete && string.IsNullOrWhiteSpace(comboBox.Text.Trim())) { comboBox.DroppedDown = true; } }
然后在EditingControlShowing里绑定这个KeyDown事件:
private void DataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { comboBoxHandler = e.Control as ComboBox; if (comboBoxHandler != null) { comboBoxHandler.IntegralHeight = false; // 没有这个MaxDropDownItems不生效 comboBoxHandler.MaxDropDownItems = 10; comboBoxHandler.DropDownStyle = ComboBoxStyle.DropDown; comboBoxHandler.AutoCompleteSource = AutoCompleteSource.ListItems; comboBoxHandler.AutoCompleteMode = AutoCompleteMode.SuggestAppend; comboBoxHandler.KeyPress += ComboBox_KeyPress; comboBoxHandler.KeyDown += ComboBox_KeyDown; // 新增绑定 comboBoxHandler.LostFocus += Combo_LostFocus; } }
2. 编辑时获取不到修改后的值?
因为编辑过程中CurrentCell.Value存的是原始值,实时输入的内容在ComboBox的Text属性里。要获取最新内容,得判断当前是否在编辑模式:
// 获取当前单元格的实际内容 string GetCurrentCellContent() { if (dgvCustom.IsCurrentCellInEditMode && comboBoxHandler != null) { return comboBoxHandler.Text.Trim(); } else { return dgvCustom.CurrentCell.Value?.ToString().Trim() ?? string.Empty; } }
如果要确保编辑结束后单元格值同步,加个CellEndEdit事件:
private void dgvCustom_CellEndEdit(object sender, DataGridViewCellEventArgs e) { if (comboBoxHandler != null) { dgvCustom.CurrentCell.Value = comboBoxHandler.Text.Trim(); comboBoxHandler = null; } }
内容的提问来源于stack exchange,提问作者Hellboy.
相关产品推荐
相关产品推荐

