Ahmed El Saeed Ahmed El Saeed - 3 months ago 17
C# Question

Convert Combobox to Textbox in Gridview C#

i have an combobox cell and i wanna convert to textbox cell after select item from the same combobox cell and convert to textbox but the problem when using

[1, DataGridView1.CurrentRow.Index] = new DataGridViewTextBoxCell()`

the cell not change until click on another cell although i'm using

Datagridview1.refresh()


the first picture (when select from combobox then it should be changed )


the second picture ( after click an another cell )

TaW TaW
Answer

DataGridViewComboBoxCells are notoriously obtuse when it comes to such a simple thing as simply and fully accepting a selected value..

This seems to work for me:

ComboBox editComboBox = null;

private void DataGridView1_EditingControlShowing(object sender, 
                           DataGridViewEditingControlShowingEventArgs e)
{
    if (e.Control is ComboBox && e.ColumnIndex == 1)
    {
        editComboBox = (ComboBox)e.Control;
        editComboBox.SelectionChangeCommitted -= editComboBox_SelectionChangeCommitted;
        editComboBox.SelectionChangeCommitted += editComboBox_SelectionChangeCommitted;
    }
}

void editComboBox_SelectionChangeCommitted(object sender, EventArgs e)
{
    DataGridView1[1, dataGridView5.CurrentRow.Index] = new DataGridViewTextBoxCell();
    DataGridView1[1, dataGridView5.CurrentRow.Index].Value =
                        editComboBox.SelectedItem.ToString();

    DataGridView1.EndEdit();
    DataGridView1[1, dataGridView5.CurrentRow.Index]cell1.Selected = false;
    editComboBox = null;
}

Note that calling EndEdit allegedly can raise an exception if no error handler is found. I don't have one and I still don't get an error. Not sure what the docs mean; maybe that it may raise an error if the data are in fact invalid..

Also note that with this design the user can not easily correct an edit, unless you provide a way to restore the dropdown..

Comments