I'm writing this application in C#, .NET 4, winforms.
I want to programatically add new row to a datagridview which is bound to a collection. When I do that I get an exception. (note: when user creates new row via datagridview (types something into new row) I have no problems).
locationBindingSource.AddNew(); //this is bound to datagridview
var row = locationsDGV.Rows[locationsDGV.Rows.Count - 2]; //get the new row
locationsDGV.CurrentCell = row.Cells[0]; //switch to new row <-throws error
Error that is thrown: System.InvalidOperationException was unhandled. Operation did not succeed because the program cannot commit or quit a cell value change.
I need to switch to a new row to ensure that user won't leave row in not validated state.
Is it possible to overcome this without disabling row validation?
Thank you for you answers.
EDIT: Bindingsource is populated with objects created by Entity Framework. When a user creates a new object, for instance "location", it is created with default values, which can't be saved to database, thus I need validation. I validate that all important fields are not empty (or filled with default values). If they are I cancel validation. I think you can easily recreate it with just a simple bindinglist of simple(one string field should be enough) objects bound to a datagridview. Then create a row validating event and validate using something similar.
Location location = (Location)locationBindingSource.Current;
if (string.isNullOrWhitespace(location.stringProperty))
e.cancel=true;