6

Używam zdarzenia (EditingControlShowing), aby włączyć autouzupełnianie w kolumnie DataGridViewComboBox.Co za dziwne zachowanie w autouzupełnianiu w kolumnie 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; 
    } 
} 

Ale ma dziwne zachowanie, kiedy wpisać kilka znaków a potem zostawić komórkę (lub prawy klawisz Tab), wartość ta nie uległa zmianie.
Ale jeśli to powtórzę, wartość zmieni się. Od Here można pobrać kod źródłowy i wideo (EXE) wyjaśniające problem.

Czy możesz mi pomóc, aby działało poprawnie?

+0

Interesujący problem i dobra praca nad poprawką! Dodałem alternatywną poprawkę, która używa nieco mniej kodu, który może ci się przydać. –

Odpowiedz

4

Wydaje się, że do tego pierwszego wjazdu na combobox zakładka nie powoduje zatwierdzenie wartości. Nie mam pojęcia, dlaczego tak jest, ale wygląda na to, że obsługa CurrentCellDirtyStateChanged i zatwierdzenie edycji naprawia to.

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

dzięki ... to też działa dla mnie .. – houssam

1

Rozwiązałem to tak:

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; 

}