Changing cell type in DGV from ComboBox to TextBox only works for row 0?
I have struggled all day trying to make my DataGridView behave. I'm using the following code to change a ComboBox cell to a TextBox, when user selects entry
It works beatifully for row 0, but for all other rows, the ComboBox remains on the screen, even though debugging says it's a TextBox cell! (inspecting CurrentCell).
Does anybody have a clue?
Here's a snippet:
void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
DataGridViewComboBoxEditingControl cb = sender as DataGridViewComboBoxEditingControl;
if (cb.SelectedIndex == 0 && dataGridViewReceivers.CurrentCell is DataGridViewComboBoxCell)
{
cb.SelectedIndexChanged -= new EventHandler(comboBox_SelectedIndexChanged);
dataGridViewReceivers.CellLeave -= new DataGridViewCellEventHandler(dataGridViewReceivers_CellLeave);
dataGridViewReceivers.EndEdit();
// Change to editing mode
int row = dataGridViewReceivers.CurrentCell.RowIndex;
dataGridViewReceivers[0, row] = new DataGridViewTextBoxCell();
dataGridViewReceivers[0, row].Value = "";
dataGridViewReceivers.BeginEdit(false);
dataGridViewReceivers开发者_如何学Go.RefreshEdit();
dataGridViewReceivers.CellLeave += new DataGridViewCellEventHandler(dataGridViewReceivers_CellLeave);
cb.SelectedIndexChanged += new EventHandler(comboBox_SelectedIndexChanged);
}
}
New rows are added using a BindingSource.AddNew().
Thanks!
EDIT:
When I call the code to replace the cell object, outside the event handler - it works! This indicates that it is worth trying a delegate...
EDIT:
Problem solved It turns out that if I remove the focus from the DGV during the replacement, it works! Simply momentarily setting the focus to a button, and back again does the trick!
For some reason, the DGV does not allow me to change the cell type when it has focus. Unselecting the cell is not enough - focus needs to be removed from the control.
This looks like a .NET bug!...
精彩评论