0
votes

I want to add a new row to datagridview after validating the row. I call my AddNewRow method inside of the RowValidated event. But it gives "Operation cannot be performed in this event handler" error.

My datagridview is not bounded any data source, and AllowUsersToAddRow property is setted to false.

DataGridView have only one column, which is named "Cost".

Here is my code;

 private void RMaterialDGV_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
    {
        DataGridView dgv = sender as DataGridView;
        if (dgv.IsCurrentRowDirty)
        {
            if(dgv.CurrentRow.Cells["Cost"].Value == null || dgv.CurrentRow.Cells["Cost"].Value.ToString().Length == 0
                || dgv.CurrentRow.Cells["Cost"].Value.ToString() == 0.ToString())
            {
                e.Cancel = true;
            }
        }
    }

    private void RMaterialDGV_RowValidated(object sender, DataGridViewCellEventArgs e)
    {
        DataGridView dgv = sender as DataGridView;
        if (dgv.CurrentRow.Index == dgv.Rows.Count - 1 && dgv.CurrentRow.Cells["Cost"].Value != null)
        {
            if (dgv.CurrentRow.Cells["Cost"].Value.ToString().Length > 0)
                AddNewRowToDGV();
        }
    }

    private void AddNewRowToDGV()
    {
        int index = RMaterialDGV.Rows.Add();
        RMaterialDGV.Rows[index].Cells["Cost"].Value = 0;
    }

I use this method to add new rows before(other projects) but never get these error.

What am I missing?

Thanks in advance.

2
Which line of code gives the error? - Chetan
@ChetanRanpariya Thank you for your message. Error is given inside the AddNewRowToDGV method; int index = RMaterialDGV.Rows.Add(); - Onur Eryilmaz
@C-PoundGuru Thank you for your message. But I checked almost every posts on the internet about this issue. There is a duplicate questions but no valid answers has given yet. - Onur Eryilmaz

2 Answers

0
votes

Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.

Instead you can add rows to your datasource. Update your AddNewRowToDGV method to something like below.

  private void AddNewRowToDGV()
        {
            var data = (DataTable) dataGridView1.DataSource;
            var row = data.NewRow();
            row["Cost"] = 1;
            data.Rows.Add(row);    
        }
0
votes

I solved this problem creating a DataTable and binding this DataTable to my DataGridView. But I can't really understand what cause the actual problem.