To prevent the DataGridView
ComboBox column text value from disappearing, you can try setting the DropDownStyle
property of the DataGridViewComboBoxColumn
to ComboBoxStyle.DropDown
. This will allow users to enter text in the ComboBox even if it is not in the list of available items.
You can set the DropDownStyle
property in code by accessing the DataGridViewComboBoxColumn
object and setting its DropDownStyle
property:
dgv.Columns["comboColumnName"].DefaultCellStyle = new DataGridViewCellStyle { NullValue = string.Empty }; (DataGridViewComboBoxColumn)dgv.Columns["comboColumnName"]).DropDownStyle = ComboBoxStyle.DropDown;
Also, in the DgvEntries_EditingControlShowing
event handler, you can try setting the EditingControl.Text
property to the selected value of the ComboBox in case it is not already set:
private void DgvEntries_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is ComboBox combo)
{
combo.SelectedIndexChanged -= Combo_SelectedIndexChanged;
combo.SelectedIndexChanged += Combo_SelectedIndexChanged;
if (combo.DropDownStyle == ComboBoxStyle.DropDown)
{
combo.Text = combo.SelectedItem?.ToString() ?? string.Empty;
}
}
}
With these changes, the ComboBox column text value should not disappear when the ComboBox_SelectedIndexChanged
event is fired.
Please, if this answer is helpful, click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please let me know.