Operation cannot be performed in this event handler

后端 未结 4 1825
日久生厌
日久生厌 2021-01-19 03:46

I\'m trying to delete a row from a DataGridView
I use two types of instuctions
A

VouchersDGV.Rows.Clear()

B



        
4条回答
  •  长情又很酷
    2021-01-19 04:28

    I had the same problem. In my case I need to save changes when the user changes selection in DataGridView. I use RowValidating event to check any changes and ask the user to save them. But when I tried to save changes inside this handler I got exception "Operation cannot be performed in this event handler."

    I was needed an event that rises after RowValidating and where I can save my changes. I didn't find such event. So I use timer for that. I start timer in RowValidating event and save my data when timer ticks.

    Here is my code:

    private void timerForSaving_Tick(object sender, EventArgs e)
    {
        if (_saveChanges)
        {
            timerForSaving.Stop();
            SaveData();
            _saveChanges = false;
        }
    }
    
    private void dataGridView1_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
    {
        if (_hasUnsavedChanges)
        {
            DialogResult dr = MessageBox.Show("Do you want to save changes?", "Question",
                                                MessageBoxButtons.YesNo, MessageBoxIcon.Question);
    
            if (dr == DialogResult.Yes)
            {
                e.Cancel = true;
                _saveChanges = true;
                timerForSaving.Start();
            }
        }
    }
    

提交回复
热议问题