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.