简体   繁体   中英

Is there anyway to prevent some event fired before end of another event?

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?

SelectionChanged is fired in the middle of handling RowsAdded because you are causing a SelectionChanged by changing the current cell within dataGridView1_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 causing SelectionChanged twice, because both lines in the handler seem to change the selection).

If you don't want dataGridView1_SelectionChanged running while in the RowsAdded handler, you need to either temporarily unsubscribe from the event:

dataGridView1.SelectionChanged -= dataGridView1_SelectionChanged;
// change the selection... 
dataGridView1.SelectionChanged += dataGridView1_SelectionChanged;

Or even better, re-design what you're doing inside the SelectionChanged handler so that it is appropriate for all instances of the event.

You can override the event you want to conrol and then put an if condition in the overriden event and control when it fires and when it does not. mahdi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM