WinForms DatagridViewComboboxColumn“输入密钥”

时间:2013-12-24 03:51:14

标签: c# .net winforms datagridview datagridviewcombobox

我有一个带有可编辑组合框列的数据网格视图,但每当我在当前组合框上按“Enter”时,我写的文字就会消失。

private void dgView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (dgView1.CurrentCell.IsInEditMode)
    {
        if (dgView1.CurrentCell.GetType() == typeof(DataGridViewComboBoxCell))
        {
            if (!((DataGridViewComboBoxColumn)dgView1.Columns[e.ColumnIndex]).Items.Contains(e.FormattedValue))
            {

                ((DataGridViewComboBoxColumn)dgView1.Columns[e.ColumnIndex]).Items.Add(e.FormattedValue);
            }
        }
    }
}

private void dgView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
    {
        ComboBox cbo = (ComboBox)e.Control;
        cbo.DropDownStyle = ComboBoxStyle.DropDown;                 
    }
}

我还尝试添加事件处理程序:“按下按键”,“按下按键”和“按键按下”,但同样的问题发生。

按“Enter”键时如何保留当前文字?

1 个答案:

答案 0 :(得分:4)

DataGridViewComboBoxColumn不接受Items集合中未包含的任何值。因此,当用户键入新值时,当前单元格在编辑后不会存储该值。您必须找到另一种方法来在编辑单元格后立即获取最后一个值。我们可以在DataGridViewComboBoxEditingControl事件处理程序中获得实际的EditingControlShowing,该控件实际上是ComboBox,我们可以处理TextChanged事件。要处理以提交新值(添加到DataGridView并在当前单元格中显示)的最佳Items事件是CellEndEdit事件。所以这是你应该做的代码,我已经测试了它,看起来它像你期望的那样工作:

//use some variable to store the last edited value
string editingValue;
//EditingControlShowing event handler
private void dataGridView1_EidtingControlShowing(object sender, 
                                  DataGridViewEditingControlShowingEventArgs e) {
  var combo = e.Control as ComboBox;
  if(combo != null){
     combo.DropDownStyle = ComboBoxStyle.DropDown;
     combo.TextChanged += (s,ev) => {
       editingValue = combo.Text;
     };
  }
}
//CellEndEdit event handler for your dataGridView1
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e){
  var comboColumn = dataGridView1.Columns[e.ColumnIndex] as DataGridViewComboBoxColumn;
  if(comboColumn != null && editingValue != "" && 
     !comboColumn.Items.Contains(editingValue)){
     comboColumn.Items.Add(editingValue);
     dataGridView1[e.ColumnIndex, e.RowIndex].Value = editingValue;
  }
}

请注意,单元格值应为string,这就是editingValue被声明为string的原因,否则,您可能需要转换Text的{​​{1}}将comboBox编辑为正确的editingValue类型。