DataGridViewCombobox列中的AutoComplete有什么奇怪的行为?

时间:2012-08-31 13:38:23

标签: c# datagridview combobox datagridviewcombobox datagridviewcomboboxcell

我正在使用(EditingControlShowing)事件在DataGridViewComboBox列中启用自动完成功能。

private void dataGridView1_EditingControlShowing(object sender,  DataGridViewEditingControlShowingEventArgs e)
{
    if (e.Control is DataGridViewComboBoxEditingControl)
    {
        ComboBox combo = (ComboBox)e.Control;
        ((ComboBox)e.Control).DropDownStyle = ComboBoxStyle.DropDown;
        ((ComboBox)e.Control).AutoCompleteSource = AutoCompleteSource.ListItems;
        ((ComboBox)e.Control).AutoCompleteMode =  System.Windows.Forms.AutoCompleteMode.SuggestAppend;
    }
}

但它有一个奇怪的行为,当我输入一些字符然后我离开单元格(Tab键或右键)时,值没有改变。
但如果我重复一遍,那么价值就会改变。 从Here,您可以下载解释问题的源代码和(EXE)视频。

你能帮助我让它正常工作吗?

2 个答案:

答案 0 :(得分:4)

似乎第一次进入组合框时,选项卡不再触发值的提交。不知道为什么会这样,但似乎处理CurrentCellDirtyStateChanged并提交编辑修复了它。

void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    // You could also check here to see if the cell in question is the combobox
    if (dataGridView1.IsCurrentCellDirty)
    {
        dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
}

答案 1 :(得分:1)

我解决了这个问题:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (e.Control is DataGridViewComboBoxEditingControl)
    {
        ComboBox combo = (ComboBox)e.Control;
        ((ComboBox)e.Control).DropDownStyle = ComboBoxStyle.DropDown;
        ((ComboBox)e.Control).AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
        ((ComboBox)e.Control).AutoCompleteSource = AutoCompleteSource.ListItems;
        combo.Validated -= new EventHandler(combo_Validated);
        combo.Validated += new EventHandler(combo_Validated);

    }
}

public static object GetPropValue(object src, string propName)
{
    if (src == null)
        return null;
    return src.GetType().GetProperty(propName).GetValue(src, null);
}

void combo_Validated(object sender, EventArgs e)
{
    Object selectedItem = ((ComboBox)sender).SelectedItem;
    DataGridViewComboBoxColumn col = (DataGridViewComboBoxColumn)dataGridView1.Columns[dataGridView1.CurrentCell.ColumnIndex];
    if (!String.IsNullOrEmpty(col.ValueMember))
        dataGridView1.CurrentCell.Value = GetPropValue(selectedItem, col.ValueMember);
    else
       dataGridView1.CurrentCell.Value = selectedItem;

}