I have DataGridView
with two columns. The first column is TextBoxCol(DataGridViewTextBoxColumn)
and the Second one is ComboBoxCol(DataGridViewComboBoxColumn)
.
How can I change the value of TextBoxCol
when ComboBoxCol
changes its selected index value?
(This should happen when selected index changed in ComboBoxCol
. Not after leaving the column, like dataGridView_CellValueChanged
)
I have read one topic with almost the same problem that I am having but I dont understand the answer(which should be correct base on the check mark). Here's the link. -Almost same topic
This answer is floating around in a couple of places.
Using the DataGridViewEditingControlShowingEventHandler will fire more events than you intend. In my testing it fired the event multiple times.
Also using the combo.SelectedIndexChanged -= event will not really remove the event, they just keep stacking.
Anyway, I found a solution that seems to work. I'm including a code sample below:
// Add the events to listen for
dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
dataGridView1.CurrentCellDirtyStateChanged += new EventHandler(dataGridView1_CurrentCellDirtyStateChanged);
// This event handler manually raises the CellValueChanged event
// by calling the CommitEdit method.
void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty)
{
// This fires the cell value changed handler below
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
// My combobox column is the second one so I hard coded a 1, flavor to taste
DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[1];
if (cb.Value != null)
{
// do stuff
dataGridView1.Invalidate();
}
}