In the code below the SelectionChanged event is fired before the end of RowsAdded,how can I make the Event atomic?
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1];
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Selected = true;
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.CurrentRow != null)
{
//Something
}
}
what should i do?
SelectionChangedis fired in the middle of handlingRowsAddedbecause you are causing a SelectionChanged by changing the current cell withindataGridView1_RowsAdded. Adding a row doesn’t cause both events to be fired — you’re causing the second event while handling the first one. (In fact, you’re probably causingSelectionChangedtwice, because both lines in the handler seem to change the selection).If you don’t want
dataGridView1_SelectionChangedrunning while in the RowsAdded handler, you need to either temporarily unsubscribe from the event:Or even better, re-design what you’re doing inside the SelectionChanged handler so that it is appropriate for all instances of the event.