What a strange behavior in AutoComplete in DataGridViewCombobox column?

前提是你 提交于 2019-12-22 05:21:48

问题


I am using the (EditingControlShowing) event to Enable AutoComplete in DataGridViewComboBox Column.

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;
    }
}

But it has a strange behavior, when I type some characters then I leave the cell (Tab or right key), the value did not change.
But if I repeat that, the value will change. From Here, you can download the source code and (EXE) video that explains the problem.

Could you please help me to make it work correctly?


回答1:


It appears that for that first entry into the combobox the tab no longer triggers the commit of the value. No idea why this is so, but it appears that handling CurrentCellDirtyStateChanged and committing the edit fixes it.

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);
    }
}



回答2:


I solved it like this :

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;

}


来源:https://stackoverflow.com/questions/12216530/what-a-strange-behavior-in-autocomplete-in-datagridviewcombobox-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!