C#, WinForms.
Maybe it's a stupid and trivial problem but I can not get out!
I have a DataGridView1
with 4 columns. I check if the value of each row, in column 1, is identical to the value of the previous row in column 2. If yes, a MessageBox
appears to inform me ... and I want to bring the focus to the cell in which there is the double value just entered. I therefore wrote this code:
private void DataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs cella)
{
if (cella.RowIndex > 0 && cella.ColumnIndex == 1)
{
var PrevCell = DataGridView1.Rows[cella.RowIndex - 1].Cells[2].Value.ToString();
if (DataGridView1.Rows[cella.RowIndex].Cells[cella.ColumnIndex].Value.ToString() == PrevCell)
{
MessageBox.Show("Amount already exists. Change the current value or the previous occurrence", "Double value, already inserted", MessageBoxButtons.OK, MessageBoxIcon.Warning);
DataGridView1.CurrentCell = DataGridView1.Rows[cella.RowIndex].Cells[cella.ColumnIndex];
DataGridView1.BeginEdit(true);
//only a test:
//return;
}
}
}
}
And the CurrentCell
works fine. The problem is that such control is carried out with the CellEndEdit
Event, when I press the Tab
key to move to the next cell (or I click with the mouse to the next cell) and therefore, even if the BeginEdit
placed me on the right cell for let me edit the value, as soon as I press Tab again, it move the changed value in the next cell. It seems that the Tab pressed before displaying the MessageBox remains in memory.
When I'm writing a double value, and MessageBox appears
When the CurrentCell and BeginEdit lead me in the correct cell to change the double value
At the end of the Event
Any idea on how to handle the problem?
You need to select the cell and call the BeginEdit method after the CellEndEdit event happens. To do that, wrap that code in a BeginInvoke block:
this.BeginInvoke(new Action(() => {
DataGridView1.CurrentCell = DataGridView1.Rows[cella.RowIndex].Cells[cella.ColumnIndex];
DataGridView1.BeginEdit(true);
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With